# leetcode #67 in cpp

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;
}
};

• 本文已收录于以下专栏：

## leetcode #114 in cpp

Given a binary tree, flatten it to a linked list in-place. For example, Given 1 ...

## leetcode #160 in cpp

Write a program to find the node at which the intersection of two singly linked lists begins. F...

## Leetcode 285. Inorder Successor in BST (Medium) (cpp)

Leetcode 285. Inorder Successor in BST (Medium) (cpp)
• Niko_Ke
• 2016年12月28日 03:38
• 242

## leetcode #139 in cpp

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa...

## leetcode #36 in cpp.

The question is to determine a Sudoku is valid.  Solution:  if a Sudoku is valid, each row, each co...

## *leetcode 138 in cpp

A linked list is given such that each node contains an additional random pointer which could point t...

## leetcode #17 in cpp

The question is : Given a digit string, return all possible letter combinations that the number coul...

## leetcode \$42 in cpp

Code: (This method is not the best one. There are other methods using two pointers) Key: a bar coul...

## *leetcode #80 in cpp

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, G...

## Leetcode 116. Populating Next Right Pointers in Each Node (Medium) (cpp)

Leetcode 116. Populating Next Right Pointers in Each Node (Medium) (cpp)
• Niko_Ke
• 2016年12月27日 02:35
• 215

举报原因： 您举报文章：leetcode #67 in cpp 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)