最少乘法次数
问题描述:给定一个正整数n,求2的n次幂,每次相乘的结果,后面也能使用。
现求至少需要多少步,能得到2^n.例如2^4,2*2=2^2,2^2*2^2=2^4,所以,答案为2。
求解:每次都是乘2,我们很容易想到2进制。现在有没有想到我们中国那句古话,叫做“擒贼先擒王”,联系到这道题上,我们可以先求转化为二进制最高位的1需要几次才能得到,举个例子,14 = 2^3+2^2+2^1,14中最高位1需要3次运算才能得到,2^2,2^1这两个数,都在最高位1运算的过程中,出现过,即都只需要1次,就可以到得,故14的答案为3+1+1=5.
上码:
#include<iostream>
using namespace std;
int main() {
int n, m, cnt, total, highest;
cin >> n;
while (n--) {
cin >> m;
total = highest = cnt = 0;
while (m) {
highest++;
if (m & 1) {
total++;
}
m >>= 1;
}
cout << highest + total - 2 << endl;
}
}