004:2的冪次方表示
阿新 • • 發佈:2018-05-27
nbsp fir 同時 但是 const tor ace fin div
描述
任何一個正整數都可以用2的冪次方表示。例如:
137=27+23+20
同時約定方次用括號來表示,即ab可表示為a(b)。由此可知,137可表示為:
2(7)+2(3)+2(0)
進一步:7=22+2+20(21用2表示)
3=2+20
所以最後137可表示為:
2(2(2)+2+2(0))+2(2+2(0))+2(0)
又如:
1315=210+28+25+2+1
所以1315最後可表示為:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
輸入一個正整數n(n≤20000)。輸出一行,符合約定的n的0,2表示(在表示中不能有空格)。樣例輸入
137
樣例輸出
2(2(2)+2+2(0))+2(2+2(0))+2(0)
我的代碼 WA
#include<cstdio> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<string> #include<map> #define DEBUG(x) cout << #x << " = " << x << endl const int MIN=0x80000000;using namespace std; int getBit(int n,int i) { return (n>>i)&1; } void change(int n) { if(n==0){ printf("0"); return; } int t=n; int cnt=0; for(int i=0;t;i++){ int b=getBit(n,i); t=t<<1; if(b){ if((31-i)==2){ printf("2"); return; } else { printf("2("); change(31-i); printf(")+"); cnt++; } } } //DEBUG(cnt); } int main() { freopen("in.txt","r",stdin); int n; cin>>n; change(n); return 0; }
參考代碼
#include<cstdio> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<string> #include<map> #define DEBUG(x) cout << #x << " = " << x << endl using namespace std; int getBit(int n,int i) { return (n>>i)&1; } void change(int n) { bool first=true; for(int i=15; i>=0; i--) { if(getBit(n,i)) { if(!first){ printf("+"); } else first=false; if(i==0) { printf("2(0)"); } else if(i==1) { printf("2"); } else { printf("2("); change(i); printf(")"); } } } } int main() { // freopen("in.txt","r",stdin); int n; cin>>n; change(n); return 0; }
方向對了,但是怎麽也得不到正確的代碼,主要是編程思維不夠成熟。從上面兩份代碼,就可以看出來。
004:2的冪次方表示