您的位置:首页 > 其它

ACM Same binary weight

2014-04-19 16:39 288 查看

Same binary weight

时间限制:300 ms | 内存限制:65535 KB
难度:3

描述
The binary weight of a positive integer is the number of 1's in its binary representation.for example,the decmial number 1 has a binary weight of 1,and the decimal number 1717 (which is 11010110101 in binary) has a binary weight of 7.Give a positive integer N,return the smallest integer greater than N that has the same binary weight as N.N will be between 1 and 1000000000,inclusive,the result is guaranteed to fit in a signed 32-bit interget.

输入The input has multicases and each case contains a integer N.输出For each case,output the smallest integer greater than N that has the same binary weight as N.样例输入
1717
4
7
12
555555

样例输出
1718
8
11
17
555557
解题思路  1. 将右起第一个“01”,改变为“10”  2. 将该“01”后面的所有“1”移动至最后


#include <iostream>
#include <string>
#include <bitset>
#include <algorithm>
using namespace std;

int main(){
int n;
while(cin >> n){
bitset<32> bitInt(n);
string strInt =bitInt.to_string();
int pos = strInt.rfind("01");
swap(strInt[pos],strInt[pos+1]);
if(pos+2 < 31) sort(strInt.begin()+pos+2,strInt.end());
cout<<bitset<32>(strInt).to_ulong()<<endl;
}
}



string rfind("01")从字符串右边找”01“然后返回”01“的位置

将01后面的1移动到最后相当于对01后面的字符串排序


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: