hihocoder#1410 : Powers of Two(水题)

来源:互联网 发布:淘宝pc端搭配套餐 编辑:程序博客网 时间:2024/06/06 09:18

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

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.

输入

One positive integer N.  

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

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

输出

The minimum number of powers of 2.

样例输入
7
样例输出
2
思路:不断把n逼近0就行了。

#include<bits/stdc++.h>using namespace std;int f(long long n){    if(n==0)return 0;    long long ans=1;    while(ans*2<=n)ans*=2;    ans=min(n-ans,2*ans-n);    return 1+f(ans);}int main(){    long long n;    scanf("%lld",&n);    cout<<f(n)<<endl;    return 0;}