https://oj.leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
/*
쉬운 문제인데 의외로 한번에 accepted 안됨.
잔 실수를 줄이고 carry 계산을 잘하는게 포인트.
*/
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int aIt = a.length()-1;
int bIt = b.length()-1;
int carry = 0;
while(aIt >= 0 && bIt >= 0) {
int aInt = (int)a.at(aIt)-48;
int bInt = (int)b.at(bIt)-48;
if((aInt+bInt+carry) == 0) {
res.insert(0, "0");
carry = 0;
} else if((aInt+bInt+carry) == 1) {
res.insert(0, "1");
carry = 0;
} else if((aInt+bInt+carry) == 2) {
res.insert(0, "0");
carry = 1;
} else {
res.insert(0, "1");
carry = 1;
}
aIt--;
bIt--;
}
while(aIt >= 0) {
int aInt = (int)a.at(aIt)-48;
if(aInt+carry == 0) {
res.insert(0, "0");
carry = 0;
} else if(aInt+carry == 1){
res.insert(0, "1");
carry = 0;
} else {
res.insert(0, "0");
carry = 1;
}
aIt--;
}
while(bIt >= 0) {
int bInt = (int)b.at(bIt)-48;
if(bInt+carry == 0) {
res.insert(0, "0");
carry = 0;
} else if(bInt+carry == 1){
res.insert(0, "1");
carry = 0;
} else {
res.insert(0, "0");
carry = 1;
}
bIt--;
}
if(aIt < 0 && bIt < 0 && carry == 1) {
res.insert(0, "1");
}
return res;
}
'풀어본 Algorithm 문제 정리' 카테고리의 다른 글
[OJ.leetcode] set-matrix-zeroes (0) | 2014.07.06 |
---|---|
[OJ.leetcode] binary-tree-level-order-traversal (0) | 2014.07.05 |
[OJ.leetcode] pascals-triangle-ii (0) | 2014.07.04 |
[OJ.leetcode] sum-root-to-leaf-numbers (0) | 2014.07.03 |
[OJ.leetcode] convert-sorted-list-to-binary-search-tree (0) | 2014.07.03 |