某公司面试题——怎样优化乘法?
要求算法尽量高效。
#include<iostream>
using namespace std;
//获得一个2的指数这个数的幂
int getMi(int num)
{
//不是2的指数则直接返回0
if(num & (num -1) != 0)
return 0;
int times = 0;
while (num >>= 1)
{
times++;
}
return times;
}
//计算x*y
int main()
{
int x = 2;//设给定的数x为2
int y = 200;//设被乘数y为200
int result = 0;
int t;
while (y)
{
t = y;
t ^= (t -1);
t &= y;//得到最低位的1
if(t != 0)
{
result += x<< getMi(t);
y ^= t;
}
}
cout<<result<<endl;
system("pause");
return 0;
}