【HihoCoder 1410 --- Powers of Two】

【HihoCoder 1410 --- Powers of Two】

題目來源:點擊進入【HihoCoder 1410 — Powers of Two】

Description

Given a positive integer N, it is possible to represent N as the sum of several positive or negative powers of 2 (± 2k for some k). For example 7 can be represented as 22 + 21 + 20 and 23 + (-20).

Your task is to find the representation which contains the minimum powers of 2.

Input

One positive integer N.

For 80% of the data: 1 <= N <= 100000

For 100% of the data: 1 <= N <= 2000000000

Output

The minimum number of powers of 2.

Sample Input

7

Sample Output

2

AC代碼(C++):

#include <iostream>
#include <algorithm>
#include <string>
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int MAXN = 1e5+5;

int fun(int n){
    int m=1;
    while(n>m) m<<=1;
    if(n==m) return 1;
    int ans1=fun(n-m/2);
    int ans2=fun(m-n);
    return min(ans1,ans2)+1;
}

int main(){
    SIS;
    int n;
    cin >> n;
    cout << fun(n) << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章