[编程题]大数的运算
Posted wqpkita
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[编程题]大数的运算相关的知识,希望对你有一定的参考价值。
题目:输入某个数,计算它乘以2的结果
#include <iostream> #include <string> #pragma warning(disable : 4996) using namespace std; string multiply2(string &str) { int len = str.size(); if (len == 0) return "0"; string result = str; int location = len - 1; //从最后一位开始计算 int locationSum = 0; //当前位置的数相加的结果 int carry = 0; //进位 int curr = 0; //计算后该位的实际值 char buffer[2]; while (location >= 0) { if (str[location] >= ‘0‘ && str[location] <= ‘9‘) { locationSum = (str[location] - ‘0‘) * 2 + carry; if (locationSum > 9) { curr = locationSum - 10; itoa(curr, buffer, 10); result[location] = buffer[0]; carry = 1; } else { curr = locationSum; itoa(curr, buffer, 10); result[location] = buffer[0]; carry = 0; } } else { //输入不合法 cerr << "invalid input" << endl; return "0"; } location--; } if (carry == 1) { string big = "1"; //最终的进位 result = big + result; } return result; } int main() { string a; getline(cin, a); string b = multiply2(a);
cout << b << endl;
return 0;
}
以上是关于[编程题]大数的运算的主要内容,如果未能解决你的问题,请参考以下文章