將一個長度最多為30位數字的十進位制非負整數轉換為二進位制數輸出
阿新 • • 發佈:2018-12-30
#include "iostream"
#include "string"
#include "cmath"
#include "vector"
#include "algorithm"
using namespace std;
vector<int> a;
string ss;
int main(){
while (cin >> ss){
while(1){
bool update = 0;
string::iterator it;
for (it = ss.begin(); it != ss.end(); it++){
if (*it != '0') {
update = 1;
break;
}
}
//
// cout << *it << endl;
//
if (!update) break;
else {
string::iterator p = ss.end() - 1;
if ((*p - '0') & 1) a.push_back(1);
else a.push_back(0);
//
// for (vector<int>::iterator i = a.begin(); i != a.end(); i++){
// printf("%d\n",*i);
// }
//
int flag = 0;
for (p = it; p != ss.end(); p++){
int temp;
temp = (flag * 10 + (*p - '0')) / 2;
flag = flag * 10 + (*p - '0') - temp * 2;
int x = p - ss.begin();
ss[x] = temp + '0';
}
// cout << *p <<endl;
}
}
if (a.empty( )) a.push_back(0);
reverse(a.begin(), a.end());
for (vector<int>::iterator i = a.begin(); i != a.end(); i++){
printf("%d",*i);
}
printf("\n");
a.clear();
}
}