📜  将给定数字乘以2,以便将其除以10

📅  最后修改于: 2021-04-23 05:18:45             🧑  作者: Mango

给定一个数字,唯一允许的操作是将数字乘以2。计算最小操作数以使该数字可被10整除。

注意:如果无法转换,请打印-1。

例子:

方法:仅当给定数字的最后一位为0时,才能将其除以10。为此,请提取输入数字的最后一位,并通过以下方式进行检查:
1)如果最后一位数字为0,那么它已经可以被10整除,因此最小步数为0。

2)如果最后一位是5,则将其乘以2将使其被10整除,因此最小步数为1。

3)如果最后一位数字是偶数或奇数(0和5除外),则将其乘以2任意次数将只会产生偶数,因此我们永远无法将其除以10。因此,步数为- 1。

C++
// C++ code for finding 
// number of operations
#include 
using namespace std;
  
int multiplyBy2(int n)
{
    int rem, value;
  
    // Find the last digit or remainder
    rem = n % 10;
    switch (rem) {
  
    // If the last digit is 0
    case 0:
        value = 0;
        break;
  
    // If the last digit is 5
    case 5:
        value = 1;
        break;
  
    // If last digit is other 
    // than 0 and 5. 
    default:
        value = -1;
    }
  
    return value;
}
  
// Driver code
int main()
{
  
    int n = 28;
    cout << multiplyBy2(n) << endl;
  
    n = 255;
    cout << multiplyBy2(n) << endl;
  
  return 0;
}


Java
// JAVA code for finding 
// number of operations
import java.io.*;
  
class GFG
{
    static int multiplyBy2(int n)
{
    int rem, value;
  
    // Find the last digit
    // or remainder
    rem = n % 10;
    switch (rem) 
    {
  
    // If the last digit is 0
    case 0:
        value = 0;
        break;
  
    // If the last digit is 5
    case 5:
        value = 1;
        break;
  
    // If last digit is other 
    // than 0 and 5. 
    default:
        value = -1;
    }
  
    return value;
}
  
// Driver code
public static void main (String[] args) 
{
    int n = 28;
    System.out.println(multiplyBy2(n));
  
    n = 255;
    System.out.println(multiplyBy2(n));
}
}
  
// This code is contributed
// by shiv_bhakt.


Python3
# Python3 code for finding number 
# of operations
def dig(argu): 
    switcher = { 
        0: 0, 
        5: 1, 
    } 
    return switcher.get(argu, -1)
      
def multiplyBy2(n):
  
    # Find the last digit or remainder
    rem = n % 10;
    return dig(rem);
  
# Driver code
n = 28;
print(multiplyBy2(n));
  
n = 255;
print(multiplyBy2(n));
          
# This code is contributed by mits


C#
// C# code for finding 
// number of operations
using System;
  
class GFG
{
    static int multiplyBy2(int n)
    {
    int rem, value;
  
    // Find the last digit
    // or remainder
    rem = n % 10;
    switch (rem) 
    {
  
    // If the last
    // digit is 0
    case 0:
        value = 0;
        break;
  
    // If the last 
    // digit is 5
    case 5:
        value = 1;
        break;
  
    // If last digit is 
    // other than 0 and 5. 
    default:
        value = -1;
        break;
    }
  
    return value;
}
  
// Driver code
public static void Main () 
{
    int n = 28;
    Console.WriteLine(multiplyBy2(n));
  
    n = 255;
    Console.WriteLine(multiplyBy2(n));
}
}
  
// This code is contributed
// by shiv_bhakt.


PHP


输出:
-1
1