Powers of Two(題目鏈接)
思路
利用遞歸签舞,返回每次最小的個(gè)數(shù)。
代碼
#include <iostream>
using namespace std;
int f(int n){
int sum = 1;
while(n > sum){//尋找恰比n大的2^k的數(shù)
sum *= 2;
}
if(sum == n)//若相等只壳,則可以直接用2^k表示
return 1;
int t1 = f(n - sum/2);//加上下一個(gè)數(shù)
int t2 = f(sum - n);//減去下一個(gè)數(shù)
if(t1 > t2)
return t2 + 1;
return t1 + 1;
}
int main(){
int n ;
cin >> n;
cout << f(n) << endl;
}