leetcode #67 in cpp
2016-05-31 02:10
429 查看
Solution:
It is the same as #66. We use 2 instead of 10 as the modulo.
Code:class Solution {
public:
string addBinary(string a, string b) {
int carry = 0;
if(a.length() < b.length()){
string temp = a;
a = b;
b = temp;
}
int alen = a.length();
int blen = b.length();
int i = 0;
while(i<alen){
if(i<blen){
if(a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry>=2){
a[alen - i - 1] = (a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry) % 2 + '0';
carry = 1;
}
else{
a[alen - i - 1] = (a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry) + '0';
carry = 0;
}
}else{
if(a[alen - i - 1] - '0' + carry>=2){
a[alen - i - 1] = (a[alen - i - 1] - '0' + carry) % 2 + '0';
carry = 1;
}else{
a[alen - i - 1] = (a[alen - i - 1] - '0' + carry) + '0';
carry = 0;
break;
}
}
i++;
}
if(carry) a = '1' + a;
return a;
}
};
It is the same as #66. We use 2 instead of 10 as the modulo.
Code:class Solution {
public:
string addBinary(string a, string b) {
int carry = 0;
if(a.length() < b.length()){
string temp = a;
a = b;
b = temp;
}
int alen = a.length();
int blen = b.length();
int i = 0;
while(i<alen){
if(i<blen){
if(a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry>=2){
a[alen - i - 1] = (a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry) % 2 + '0';
carry = 1;
}
else{
a[alen - i - 1] = (a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry) + '0';
carry = 0;
}
}else{
if(a[alen - i - 1] - '0' + carry>=2){
a[alen - i - 1] = (a[alen - i - 1] - '0' + carry) % 2 + '0';
carry = 1;
}else{
a[alen - i - 1] = (a[alen - i - 1] - '0' + carry) + '0';
carry = 0;
break;
}
}
i++;
}
if(carry) a = '1' + a;
return a;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解