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