【STL】NYOJ 412 Same binary weight (bitset)
題目鏈接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=412
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
看到問題後沒有任何思路,在查看討論區以後發現是使用STL中的bitset來解決的
大體看完了bitset的用法
或許暴力的方法是可行的,每次+1逐一嘗試
1 #define _CRT_SBCURE_NO_DEPRECATE 2 #include <bitset> 3 #include <cstdio> 4 #include <cstring> 5 #include <iostream> 6 7 using namespace std;8 9 int main() 10 { 11 int n; 12 while(scanf("%d",&n)!=EOF) 13 { 14 bitset<32> b(n); 15 int nlen = b.count(); 16 int ilen; 17 for(int i = n+1;;i++) 18 { 19 bitset<32> bb(i); 20 ilen = bb.count(); 21 if(nlen == ilen) 22 { 23 cout << i << endl; 24 break; 25 } 26 } 27 } 28 29 return 0; 30 }
但是提交後超時了,看來需要找更快的方法,看完別人的題解後來自己找一下規律解決問題
將十進制轉化為二進制
4 :00000100
8 :00001000
7 :00000111
11:00001011
12:00001100
17:00010001
1717:0011010110101
1718:0011010110110
1.從右到左發現的第一個01都變成了10
2.發現的第一個01的左邊是沒有變化的
3.01右邊的1都移動到了最右邊
(其實我也不知道怎麽發現的這麽神奇的規律 emmmm...)
一道比較神奇的題目
接下來的工作就簡單些了,根據發現的規律來實現代碼
#define _CRT_SBCURE_NO_DEPRECATE #include <bitset> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; int main() { int n; while(scanf("%d",&n)!=EOF) { bitset<32> b(n); int i,coun = 0; for(i = 0;i < 32;i++) { if(b[i] == 1) coun++; if(b[i] == 1 && b[i+1] == 0) { b[i] = 0; b[i+1] = 1; break; } } int j = i-1; for(int i = 0;i <= j;i++) { if(i < coun-1) b[i] = 1; else b[i] = 0; } cout << b.to_ulong() << endl; } return 0; }
【STL】NYOJ 412 Same binary weight (bitset)