【hihoCoder 1410】Powers of Two

Powers of Two

思路

利用递归,返回每次最小的个数。

代码

#include <iostream>
using namespace std;

int f(int n){
    int sum = 1;
    while(n > sum){//寻找恰比n大的2^k的数
        sum *= 2;
    }
    if(sum == n)//若相等,则可以直接用2^k表示
        return 1;
    int t1 = f(n - sum/2);//加上下一个数
    int t2 = f(sum - n);//减去下一个数
    if(t1 > t2)
        return t2 + 1;  
    return t1 + 1;  
}

int main(){
    int n ;
    cin >> n;
    cout << f(n) << endl;
}

猜你喜欢

转载自blog.csdn.net/Side__/article/details/80947145
two