📜  将数字乘以10而不使用乘法运算符

📅  最后修改于: 2021-04-29 17:10:43             🧑  作者: Mango

给定一个数字,任务是将其乘以10,而不使用乘法运算符?。
例子:

Input : n = 50
Output: 500
// multiplication of 50 with 10 is = 500

Input : n = 16
Output: 160
// multiplication of 16 with 10 is = 160

解决此问题的一个简单方法是运行一个循环,然后将n与自身相加10次。在这里,我们需要执行10个操作。
更好的解决方案是使用位操作。我们必须将n乘以10即; n * 10,我们可以将其写为n *(2 + 8)= n * 2 + n * 8 ,由于不允许使用乘法运算符,因此可以使用左移按位运算运算符。因此n * 10 = n << 1 + n << 3。

C++
// C++ program to multiply a number with 10 using
// bitwise operators
#include
using namespace std;
 
// Function to find multiplication of n with
// 10 without using multiplication operator
int multiplyTen(int n)
{
    return (n<<1) + (n<<3);
}
 
// Driver program to run the case
int main()
{
    int n = 50;
    cout << multiplyTen(n);
    return 0;
}


Java
// Java Code to Multiply a number with 10
// without using multiplication operator
import java.util.*;
 
class GFG {
     
    // Function to find multiplication of n
    // with 10 without using multiplication
    // operator
    public static int multiplyTen(int n)
    {
        return (n << 1) + (n << 3);
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int n = 50;
        System.out.println(multiplyTen(n));
        
    }
}
   
// This code is contributed by Arnav Kr. Mandal.


Python 3
# Python 3 program to multiply a
# number with 10 using bitwise
# operators
 
# Function to find multiplication
# of n with 10 without using
# multiplication operator
def multiplyTen(n):
 
    return (n << 1) + (n << 3)
 
# Driver program to run the case
n = 50
print (multiplyTen(n))
 
# This code is contributed by
# Smitha


C#
// C# Code to Multiply a number with 10
// without using multiplication operator
using System;
 
class GFG {
     
    // Function to find multiplication of n
    // with 10 without using multiplication
    // operator
    public static int multiplyTen(int n)
    {
        return (n << 1) + (n << 3);
    }
     
    // Driver Code
    public static void Main()
    {
        int n = 50;
        Console.Write(multiplyTen(n));
         
    }
}
     
// This code is contributed by Nitin Mittal.


PHP


Javascript


输出:

500