Created
October 14, 2015 16:34
-
-
Save k06a/84db869a8014ffdf7eb7 to your computer and use it in GitHub Desktop.
Add two decimal number stored in strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string add(const string & s1, const string & s2) | |
{ | |
int flag = 0; | |
string ret(std::max(s1.size(),s2.size())+1, '0'); | |
for (int i = 0; i < ret.size(); i++) { | |
int v = (i < s1.size() ? s1[s1.size()-1-i]-'0' : 0) | |
+ (i < s2.size() ? s2[s2.size()-1-i]-'0' : 0) + flag; | |
flag = v/10; | |
v -= flag*10; | |
ret[ret.size()-1-i] = v+'0'; | |
} | |
while (ret[0] == '0') | |
ret.erase(ret.begin()); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment