Same binary weight
-
描述
-
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.
-
The input has multicases and each case contains a integer N.
题意: 给一个数字N ,其二进制含有几个1就表示它 weight 是多少,现在求一个新的数字ans ,ans 大于 N且ans的weigh 等于 N的weight;
新学bitset <> :\
#include<stdio.h>
#include<bitset>
using namespace std;
int main()
{
// freopen("in.in","r",stdin);
int n;
while(~scanf("%d",&n))
{
bitset<32>cur(n);
int st;
for(st=0;st<32;st++)
if(cur[st]&&!cur[st+1])break;
cur[st+1]=1;
cur[st]=0;
int num=0;
for(int i=0;i<st;i++)if(cur[i]) num++;
for(int i=0;i<num;i++) cur.set(i);
for(int i=num;i<st;i++) cur.reset(i);
printf("%d\n",cur.to_ulong());
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
int cur[40];
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
// freopen("in.in","r",stdin);
int n;
while(~scanf("%d",&n))
{
int len=0;
while(n){
cur[len++]=n%2;
n/=2;
} // 把N转化成二进制 ,倒着存在cur[] 里面
for(int i=0;i<len;i++)
{
if(cur[i]) //找到第一个为1的位置
{
int ok=1;
for(int j=i+1;j<len-1;j++)
{
if(cur[j]==0) // 找到i前面且最近为0 的位置
{
ok=0;
cur[i]=0;cur[j]=1; // e.g. 11111 0 011……
sort(cur,cur+j,cmp); // i=0;j=2; ->01111 1 011…… 改变排序之后成 11110 1 011……
break;
}
}
if(ok) // 前面全是1 的情况 0011111 -> 00111101 -> 11110001
{
cur[len-1]=0;
cur[len++]=1;
sort(cur,cur+len-1,cmp);
}
break;
}
}
int ans=0;
int tp=1;
for(int i=0;i<len;i++)
{
ans+=cur[i]*tp;
tp*=2;
}
printf("%d\n",ans);
}
return 0;
}