Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
43 lines (42 loc) · 1.09 KB

File metadata and controls

43 lines (42 loc) · 1.09 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.yangchd.leetcode.easy;
/**
* @author yangchd 2018/10/24
*
* 67.Add Binary
* Given two binary strings, return their sum (also a binary string).
* The input strings are both non-empty and contains only characters 1 or 0.
*
* Example 1:
* Input: a = "11", b = "1"
* Output: "100"
*
* Example 2:
* Input: a = "1010", b = "1011"
* Output: "10101"
*
*/
public class AddBinary {
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int m = a.length() - 1;
int n = b.length() - 1;
int carry = 0;
while (m >= 0 || n >= 0) {
int sum = carry;
if (m >= 0) {
sum += a.charAt(m--) - '0';
}
if (n >= 0) {
sum += b.charAt(n--) - '0';
}
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) {
sb.append(carry);
}
return sb.reverse().toString();
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.