HUST 1568 Next K-Bit Number(模拟/搜索)
Next K-Bit Number
Time Limit: 1 Sec Memory Limit: 128 MBSubmissions: 368 Solved: 138
Description
Our problem is to create a function: uint NextKBitNumber(uint), which given an unsigned integer X with K bits set, returns the immediately larger unsigned integer also with K bits set. For example, if X = 12 (base 10) = 1100(base 2), X has 2 bits set, then the next number with 2 bits set(NextKBitNumber) is 17(base 10) = 10001(base 2).
Input
The first line is the number of test cases,there are at most 1001 cases.
Then each line is a case with an unsigned number X.
It is guaranteed that all answers are in unsigned 32-bit Integer.
Output
For each cases, the first line is “Case #k:”, where k is the case index based 1.
The second line is the NextKBitNumber of X.
Sample Input
2 12 7
Sample Output
Case #1: 17 Case #2: 11
题目大意:给定一个32位无符号整数,求出一个数是第一个比它大并且它们转换成二进制时1的个数相等。
思路:有两个,一是模拟,二是暴搜。
模拟就是把这个数换成二进制,然后求出1的个数相等,且比它大的最小的二进制数,再转换成十进制输出。
View Code
1 # include<stdio.h> 2 # include<string.h> 3 # include<iostream> 4 using namespace std; 5 int a[50]; 6 int main() 7 { 8 int cas,i,j,T,n; 9 scanf("%d",&T); 10 for(cas=1;cas<=T;cas++){ 11 scanf("%d",&n); 12 printf("Case #%d:\n",cas); 13 int cnt=0; 14 int temp; 15 while(n) //转换成二进制,结果保存在一个数组里边 16 { 17 temp=n%2; 18 a[cnt++]=temp; 19 n=n/2; 20 } 21 int num=0,flag=0; //num表示1的个数,flag表示是否已经找到第一个1 22 for(i=0;i<cnt;i++){ 23 if(flag) 24 { 25 if(a[i]==0){ //求出比原来的二进制大的最小的二进制数 26 a[i]=1; 27 for(j=0;j<num-1;j++) 28 a[j]=1; 29 for(;j<i;j++) 30 a[j]=0; 31 break; 32 } 33 } 34 if(a[i]) num++; 35 if(!flag && a[i]) 36 { 37 flag=1; 38 } 39 } 40 if(i>=cnt){ //如果从第一个1开始到最后没有出现过0,这时不得不进位 41 a[cnt++] = 1; 42 for(i=0;i<num-1;i++) 43 a[i]=1; 44 for(;i<cnt-1;i++) 45 a[i]=0; 46 } 47 int ans=0; //转化成十进制 48 for(i=cnt-1;i>=0;i--) ans=ans*2+a[i]; 49 printf("%d\n",ans); 50 } 51 return 0; 52 }
暴搜就是从比这个数大的下一个数开始,直到找到一个数的二进制时1的个数和它相等的数,即为结果。
View Code
1 # include<stdio.h> 2 # include<string.h> 3 # include<iostream> 4 using namespace std; 5 int num(int x) //计算整数转化成二进制数时包含1的个数 6 { 7 int cnt=0; 8 while(x) 9 { 10 if(x%2==1) cnt++; 11 x=x/2; 12 } 13 return cnt; 14 } 15 int main() 16 { 17 int cas,n,i,T; 18 scanf("%d",&T); 19 for(cas=1; cas<=T; cas++) 20 { 21 scanf("%d",&n); 22 int temp = num(n); 23 printf("Case #%d:\n",cas); 24 for(i=n+1;;i++) 25 { 26 if(num(i)==temp) break; 27 } 28 printf("%d\n",i); 29 } 30 return 0; 31 }
把每一件简单的事情做好,就是不简单;把每一件平凡的事情做好,就是不平凡!相信自己,创造奇迹~~