标签:https size_t cin namespace nal gre blog 小程序 term
1 //大数相加(十进制),用string处理 2 #include <iostream> 3 #include <string> 4 #include <algorithm> 5 6 using namespace std; 7 8 //输入数据合法性检查,数字必须在0-9范围内 9 bool IsVaild(const string& num1,const string& num2) 10 { 11 for(auto val:num1) 12 { 13 if(!(val>=‘0‘ && val-‘0‘<=‘9‘)) 14 return false; 15 } 16 for(auto val:num2) 17 { 18 if(!(val>=‘0‘ && val<=‘9‘)) 19 return false; 20 } 21 return true; 22 } 23 24 string greatNumberAdd(string num1,string num2) 25 { 26 const size_t len1=num1.length(); 27 const size_t len2=num2.length(); 28 const size_t n=len1>len2 ? len1 :len2; 29 reverse(num1.begin(),num1.end()); 30 reverse(num2.begin(),num2.end()); 31 32 string result; 33 int carry=0; 34 for(size_t i=0;i<n;++i) 35 { 36 const int num1i = i<len1 ? num1[i]-‘0‘ :0; 37 const int num2i = i<len2 ? num2[i]-‘0‘ :0; 38 const int val = (num1i+num2i+carry)%10; 39 carry=(num1i+num2i+carry)/10; 40 result.insert(result.begin(),val+‘0‘); 41 } 42 if(1==carry)//若最前面有进位,则插入‘1‘ 43 result.insert(result.begin(),‘1‘); 44 45 return result; 46 } 47 48 int main() 49 { 50 string num1,num2; 51 while(cin>>num1>>num2) 52 { 53 if(IsVaild(num1,num2)) 54 cout<<greatNumberAdd(num1,num2)<<endl; 55 else 56 cout<<"输入数据不合法"<<endl; 57 } 58 return 0; 59 }
代码借鉴了牛客网“赞一下”用户的思想,在此感谢,原题目参见https://www.nowcoder.com/questionTerminal/5821836e0ec140c1aa29510fd05f45fc?orderByHotValue=0&mutiTagIds=578_579&page=2&onlyReference=false。
标签:https size_t cin namespace nal gre blog 小程序 term
原文地址:http://www.cnblogs.com/xiaoxi666/p/7256527.html