长整数相加
题目链接:https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6?tpId=37&&tqId=21280&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking
解法1:
参考:https://www.nowcoder.com/profile/7467293/codeBookDetail?submissionId=12310134
疑问:没有区分正负情况,竟然AC了
#include<iostream> #include<string> using namespace std; int main() { string str1; string str2; while(cin>>str1>>str2) { int len1=str1.length(); int len2=str2.length(); int len=len1>len2?len1:len2; for(int i=0;i<len;i++) { if(i>len1-1) str1='0'+str1; if(i>len2-1) str2='0'+str2; } string result=""; int count=0; for(int i=len-1;i>=0;i--) { result+=(str1[i]-'0'+str2[i]-'0'+count)%10+'0'; count=(str1[i]-'0'+str2[i]-'0'+count)/10; } if(count==1) { result+='1'; } if(count==-1) { result+='1'; result+='-'; } for(int i=result.length()-1;i>=0;i--) { cout<<result[i]; } cout<<endl; } return 0; }
解法2:
疑惑:没有考虑正负情况,竟然AC了
链接:https://www.nowcoder.com/questionTerminal/49e772ab08994a96980f9618892e55b6 来源:牛客网 #include <bits/stdc++.h> using namespace std; int main() { string str1, str2; while (cin >> str1>> str2) { while(str1.size()<str2.size()) { str1="0"+str1; } while(str1.size()>str2.size()) { str2="0"+str2; } int num=0; int carry=0; for(int i=str1.size()-1;i>=0;i--) { num = str1[i]-'0'+str2[i]-'0'+carry; str1[i] = num%10+'0'; carry = num/10; } if(carry) str1="1"+str1; cout<<str1<<endl; } system("pause"); return 0; }