ACM Same binary weight

OpenSoucre發表於2014-04-19

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後面的字串排序



相關文章