美文网首页
【hihoCoder 1410】Powers of Two

【hihoCoder 1410】Powers of Two

作者: Siding | 来源:发表于2018-10-04 16:37 被阅读0次

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;
}

相关文章

网友评论

      本文标题:【hihoCoder 1410】Powers of Two

      本文链接:https://www.haomeiwen.com/subject/febxaftx.html