LeetCode:. 08.05 recursive multiplication face questions

Interview questions 08.05. Recursive multiplication

Topics requirements:

Recursive multiplication. Write a recursive function, operator * is not used, to achieve the multiplication of two positive integers. You can use the plus, minus, displacement, but mean number.

 

Problem-solving ideas:

Thinking 1: Direct addition of the multiplication into a plurality of n, comparing direct violence;

Wherein determining the number of small, then a large number of data are added, a total of n plus.

 

2 ideas:

Using 1 bit arithmetic, binary bits, 2 ^ a difference between two adjacent bits;

2. The same numbers into the two maximum and minimum;

3. By determining the lowest bit is 1, shift operation, and each shift are added together.

例子:A = 9, B = 7; A x B = 9 x (2^2+2^1+2^0)=9<<2+9<<1+9;

 1 class Solution {
 2 public:
 3     int multiply(int A, int B) 
 4     {
 5         int num=0;
 6         return (A > B)? mult(B, A, num):mult(A, B, num);
 7     }
 8 
 9     int mult(int n, int data, int &num)
10     {
11         // if (n==1)
12         // {
13         //     num=num+data;
14         //     return num;
15         // }
16         // num=num+data;
17         // --n;
18         // mult(n, data, num);
19         // return num;
20         if(n== 0) return 0;
21         for (int i=0; n!=0; i++)
22         {
23             if (n&1)
24             {
25                 num += data<<i;  
26                 // data=data<<i;
27                 // num +=data;
28 } 29 n=n>>1; 30 } 31 return num; 32 } 33 };

 

Guess you like

Origin www.cnblogs.com/Tavi/p/12515942.html