题解 | #10进制 VS 2进制#
10进制 VS 2进制
https://www.nowcoder.com/practice/fd972d5d5cf04dd4bb4e5f027d4fc11e
#include <iostream> #include<vector> using namespace std; //大整数 string Divide(string s,int a) { int remainder=0; for(int i=0;i<s.size();i++) { int current=remainder*10+s[i]-'0'; s[i]=current/a+'0'; remainder=current%a; } int i=0; while(s[i]=='0')i++; return s.substr(i); } string Multiply(string s,int a) { int carry=0; for(int i=s.size()-1;i>=0;i--) { int current=(s[i]-'0')*a+carry; s[i]=current%10+'0'; carry=current/10; } if(carry!=0)s="1"+s; return s; } string Add(string s,int a) { int carry=a; for(int i=s.size()-1;i>=0;i--) { int current=s[i]-'0'+carry; s[i]=current%10+'0'; carry=current/10; } if(carry)s="1"+s; return s; } int main() { string s; while (cin >> s) { // 注意 while 处理多个 case vector<int>array; while(s.size()!=0) { int last=s[s.size()-1]-'0'; array.push_back(last%2); s=Divide(s,2); //cout<<s<<endl; } //保存的时候已经逆序了 string ans="0"; for(int i=0;i<array.size();i++) { ans=Multiply(ans,2); ans=Add(ans,array[i]); } cout<<ans<<endl; } } // 64 位输出请用 printf("%lld")