题解 | #10进制 VS 2进制#
10进制 VS 2进制
https://www.nowcoder.com/practice/fd972d5d5cf04dd4bb4e5f027d4fc11e
//错误重现:string ten="0";//!!!!!!!这个地方一定要赋值,不然ten后续[]操作都为空 //掌握字符串各种进制的转换 #include <iostream> #include <vector> //#include <cmath> using namespace std; string Divide(string str,int x)//字符串除x操作 { int remainder=0; for(int i=0;i<str.size();i++) { int current=str[i]-'0'+remainder*10; str[i]=current/x+'0'; remainder=current%x; } int i=0; while(str[i]=='0') { i++; } return str.substr(i); } string Multiply(string str,int x )//字符串乘x { int cf=0;//进位 for(int i=str.size()-1;i>=0;i--) { int current=cf+(str[i]-'0')*x; str[i]=current%10+'0'; cf=current/10; } if(cf==1) str="1"+str; return str; } string Add(string str,int x)//字符串加x { int cf=x;//个位的进位就是要加的数x for(int i=str.size()-1;i>=0;i--) { int current=str[i]-'0'+cf; str[i]=current%10+'0'; cf=current/10; } if(cf==1) str="1"+str; return str; } int main() { string str; while(cin>>str) { vector<int> binary;//从前往后就是逆序二进制字符串 while(str.size()!=0) { binary.push_back((str[str.size()-1]-'0')%2); str=Divide(str,2); } string answer="0";//十进制串 for(int i=0;i<binary.size();i++) { answer=Multiply(answer,2); answer=Add(answer,binary[i]); } cout<<answer<<endl; } return 0; }