看了这篇博客才发现少了348这种情况(http://www.cnblogs.com/yewei/archive/2012/09/21/2696499.html)
#include<bits/stdc++.h> using namespace std; void show(string x) { int pow=1; int s=0; //cout<<"--"<<endl; for(int i=x.length()-1;i>=0;i--) { //cout<<"--"<<endl; s=s+(int)(x[i]-'0')*pow; pow=pow*2; } cout<<s<<endl; } string change(long long x) { stack<int>a; while(x) { int y=x%2; x=x/2; a.push(y); } string y=""; while(a.size()) { y=y+char('0'+a.top()); a.pop(); } return y; } int main() { long long x=4; while(cin>>x) { string a=change(x); int find=0; for(int i=a.length()-1;i>0;i--) { if(a[i]=='1'&&a[i-1]=='0') { swap(a[i],a[i-1]); find=i; //cout<<"find:"<<find<<endl; break; } } if(find==0) { a="0"+a; int x0=0,x1=0; for(int i=a.length()-1;i>=0;i--) { if(a[i]=='1') x1++; else x0++; } a="1"; for(int i=1;i<=x0;i++) a=a+'0'; for(int i=1;i<x1;i++) a=a+'1'; } else { int count1=0,count0=0; for(int i=find+1;i<a.length();i++) { if(a[i]=='1')count1++; else count0++; } int i=find+1; for(i=find+1;count0--;i++) { a[i]='0'; } for(;count1--;i++) { a[i]='1'; } } //cout<<a<<endl; show(a); } }
