C++ 面試題之兩個超過25位的數相加求和
上次有個兄弟面試碰到的,在這裡記錄下
void calculateAdd()
{
string str1 = "2142135213214235231323241";
string str2 = "809327498327413628164321434214";
string result = "";
cout << "str1的長度為:" << str1.length() <<endl;
cout << "str2的長度為:" << str2.length() <<endl;
int quotient = 0;
int remainder = 0;
int count = 0;
int strNum1 = str1.length();
int strNum2 = str2.length();
int max = strNum1 > strNum2 ? strNum1: strNum2;
cout << "max的長度為:" << max <<endl;
while (max > 0) {
strNum1--;
strNum2--;
max--;
int nStr1 = strNum1 >= 0 ? ((int)(str1.at(strNum1)) - 48):0;
int nStr2 = strNum2 >= 0 ? ((int)(str2.at(strNum2)) - 48):0;
count = nStr1 + nStr2 + quotient;
if (count > 9){
quotient = count / 10;
remainder = count % 10;
}else{
quotient = 0;
remainder = count;
}
result = (char)(remainder+48) + result;
}
if(quotient > 0){
result = (char)(quotient+48) + result;
}
cout << "result的長度為:" << result.length() <<endl;
cout<<"----------和為:"<<result.c_str()<<endl;
}