acm-Same binary weight

来源:互联网 发布:火炬之光2for mac汉化 编辑:程序博客网 时间:2024/04/26 06:33

Same binary weight

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

The binary weight of a positive  integer is thenumber of 1's in its binary representation.for example,the decmialnumber 1 has a binary weight of 1,and the decimal number 1717(which is 11010110101 in binary) has a binary weight of 7.Give apositive integer N,return the smallest integer greater than N thathas the same binary weight as N.N will be between 1 and1000000000,inclusive,the result is guaranteed to fit in a signed32-bit interget.

输入
The input has multicases and each case contains a integerN.
输出
For each case,output the smallest integer greater than N that hasthe same binary weight as N.
样例输入
17174712555555
样例输出
171881117555557
来源
topcoder
代码:
#include
#include
#include
#include
using namespace std;
int main()
{
 int n;
 int i,j,count;
 while(scanf("%d",&n)!=EOF)
 {
  bitset<32> b;
  i=0;
  while(n)
  {
   if(n&1)
    b.set(i);
   i++;
   n>>=1; 
  }
  count=0;
  for(j=0;j
  {
   if(b.test(j))
   {
    count++;
    b.reset(j);
    if(!b.test(j+1)) 
    {
     b.set(j+1);
     break; 
    }
   
  }
  for(j=0;j
   b.set(j);
  printf("%d\n",b.to_ulong());
 }
 return 0; 
}
原创粉丝点击