Created
December 1, 2016 02:52
-
-
Save taisyo7333/5ceefe028d8f901a233bb6975de06d7d to your computer and use it in GitHub Desktop.
leetcoode 415.
This file contains hidden or 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
// https://leetcode.com/problems/add-strings/ | |
// absにはまった。オーバーロード関数が多数あるため、引数を明示的にキャストしないと、目的の型で戻り値が得られない。 | |
class Solution { | |
public: | |
string addStrings(string num1, string num2) { | |
// 反転 : 逆方向から計算したほうが計算しやすい。 | |
reverse(num1.begin(),num1.end()); | |
reverse(num2.begin(),num2.end()); | |
// add padding zero | |
int numPadding = abs((int)(num1.size()-num2.size())); | |
string padding(numPadding,'0'); | |
if(num1.size() > num2.size()) { | |
num2 = num2 + padding; | |
} else { | |
num1 = num1 + padding; | |
} | |
// add each digits | |
vector<int> v; | |
for(int i = 0 ; i < num1.size(); i++) { | |
int n1 = (num1[i] - 0x30); | |
int n2 = (num2[i] - 0x30); | |
v.push_back(n1 + n2); | |
} | |
// 繰上げ | |
for(int i = 0 ; i < v.size() ; i++){ | |
if( v[i] < 10 ) { | |
continue; | |
} | |
const auto num = v[i]; | |
v[i] = num % 10; | |
if(i == v.size() - 1) { | |
v.push_back(1); | |
} else { | |
v[i+1] += 1; | |
} | |
} | |
// 文字列化 | |
string output; | |
for(int i= 0 ; i < v.size() ; i++ ) { | |
output.push_back((char)(v[i] + 0x30)); | |
} | |
// 反転した状態なので元に戻す | |
reverse(output.begin(),output.end()); | |
return output; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment