题目:输入某个数,计算它乘以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; }
原文地址:https://www.cnblogs.com/wqpkita/p/9610219.html
时间: 2024-10-17 08:23:56