more katas
This commit is contained in:
53
Sum Strings as Numbers/main.cpp
Normal file
53
Sum Strings as Numbers/main.cpp
Normal file
@@ -0,0 +1,53 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
|
||||
std::vector<std::string> sort_size(std::string &a, std::string &b){
|
||||
if(a.size() <= b.size()){
|
||||
return {a, b};
|
||||
} else {
|
||||
return {b, a};
|
||||
}
|
||||
}
|
||||
|
||||
void pad_zeros(std::string &input, int zeros_to_pad){
|
||||
input.insert(0, zeros_to_pad, '0');
|
||||
}
|
||||
|
||||
std::string sum_strings(std::string a, std::string b) {
|
||||
a.erase(0, std::min(a.find_first_not_of('0'), a.size()-1));
|
||||
b.erase(0, std::min(b.find_first_not_of('0'), b.size()-1));
|
||||
auto shortest = sort_size(a, b);
|
||||
int size_diff = abs(a.size() - b.size());
|
||||
|
||||
pad_zeros(shortest[0], size_diff);
|
||||
|
||||
int overflow = 0;
|
||||
char insert;
|
||||
std::string result;
|
||||
for(int i=shortest[0].size()-1; i>=0; i--){
|
||||
int val1 = shortest[1][i] - '0';
|
||||
int val2 = shortest[0][i] - '0';
|
||||
int temp = val1 + val2 + overflow;
|
||||
if(temp>9){
|
||||
overflow = temp / 10;
|
||||
insert = std::to_string(temp)[1];
|
||||
} else {
|
||||
overflow = 0;
|
||||
insert = std::to_string(temp)[0];
|
||||
}
|
||||
result.insert(0, 1, insert);
|
||||
}
|
||||
|
||||
if(overflow > 0)
|
||||
result.insert(0, std::to_string(overflow));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int main(){
|
||||
std::string test1 = "99";
|
||||
std::string test2 = "2";
|
||||
std::cout << sum_strings(test1, test2);
|
||||
}
|
||||
Reference in New Issue
Block a user