思路
对输入字符串对2取模再除以2,对于字符串取模运算,转换为对字符串最低位数进行取模;字符串除法则是把字符串从高到低逐位除以除数,如果不能整除,那么保留它除以除数的余数,余数乘10后和低位相加后一起处理,由于有前置0,故应取首个非0位之后的字符。
程序代码
#include <iostream>
#include <vector>
using namespace std;
int qu_yu(string a) { //取余
return (a[a.length() - 1] - '0') % 2;
}
void zi_fu_chuan_chu_fa(string& a) { //字符串除法
int temp = 0;
int i = 0;
while (a[i] == '0') {
++i;
}
for (; i < a.length(); ++i) {
int x = (a[i]-'0') + temp;
a[i] = (x / 2) + '0';
temp = x % 2 * 10;
}
}
int main()
{
string ss;
while (cin >> ss) {
vector<int> re;
if (ss == "0")
re.push_back(0);
else {
bool t = true;
while (t) {
re.push_back(qu_yu(ss));
zi_fu_chuan_chu_fa(ss);
for (int i = 0; i < ss.length(); ++i) { //看字符串是否为全0
if (ss[i] != '0') break;
if ((i == ss.length() - 1) && ss[i] == '0') t = false;
}
}
}
for (int i = re.size()-1; i>=0; --i) {
cout << re[i];
}
cout << endl;
}
}