an easy problem(貪心)


An Easy Problem
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8333   Accepted: 4986

Description

As we known, data stored in the computers is in binary form. The problem we discuss now is about the positive integers and its binary form. 

Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I, and the number of '1's in whose binary form is the same as that in the binary form of I. 

For example, if "78" is given, we can write out its binary form, "1001110". This binary form has 4 '1's. The minimum integer, which is greater than "1001110" and also contains 4 '1's, is "1010011", i.e. "83", so you should output "83".

Input

One integer per line, which is I (1 <= I <= 1000000). 

A line containing a number "0" terminates input, and this line need not be processed.

Output

One integer per line, which is J.

Sample Input

1
2
3
4
78
0

Sample Output

2
4
5
8
83

Source

POJ Monthly,zby03
【思路】:會發現 78 :1001110  
                        83:1010011
  83的二進制是78二進制從右往做掃掃到01,將這個1左移一位,剩下的1右移
網上有種方法一行代碼的大神 渣渣我直接看不懂 
這是哪門子貪心?orz  bb我要狗帶了
【代碼】
 1 //    Presentation Error(展示錯誤orz)    mlgb沒換行符報錯 第一次出現這種錯誤整個人都蒙圈了 
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<cstdlib>
 5 #include<cstring>
 6 using namespace std;
 7 int er[100001];
 8 int main()
 9 {
10     int n;
11     while(cin>>n&& n)//當能輸出且不為零時 
12     {
13         int k=0,tot=0;
14         memset(er,0,sizeof(er));
15         while(n)//計算二進制 
16         {
17             er[++k]=n%2;
18             n/=2;
19         }
20         k++;
21         for(int i=1;i<=k;i++)
22         {
23             if(er[i]==1)//找1的個數 
24             {
25                 tot++;
26                 er[i]=0;
27             if(er[i+1]==0)//從低位到高位找01 
28             {
29                 er[i+1]=1;//找到了就改為1; 相當於左移了 
30                 break;
31                 }    
32             }
33         }
34         for(int i=1;i<=tot-1;i++)
35         {
36             er[i]=1;//將tot-1個1放在末尾,(右移),tot-1是因為其中一個左移了 
37         }
38         int sum=0;
39         for(int i=k;i>=1;i--)//將二進制轉換為十進制輸出 
40         {
41             sum=sum*2+er[i];
42         }
43         printf("%d\n",sum);
44     }
45     return 0;
46 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM