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
executable file
·
90 lines (66 loc) · 2.18 KB

File metadata and controls

executable file
·
90 lines (66 loc) · 2.18 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
E
方法一:土办法没技术把binary换成数字加起来再换成binary如果input很大那么很可能int,long都hold不住不保险
方法二:一般方法string化为charArray,然后逐位加起最后记得处理多余的一个carry on
```
/*
Add Binary
Given two binary strings, return their sum (also a binary string).
Example
a = 11
b = 1
Return 100
Tags Expand
String Binary Facebook
*/
/*
//Thougths:
1. Turn string binary format into integer
2. add integer
3. turn integer into binary string
Note: this just test if we know how to manipulate string/binary/Integer
*/
public class Solution {
/**
* @param a a number
* @param b a number
* @return the result
*/
public String addBinary(String a, String b) {
if (a == null || b == null || a.length() == 0 || b.length() == 0) {
return null;
}
int decimalA = Integer.parseInt(a, 2);
int decimalB = Integer.parseInt(b, 2);
int sum = decimalA + decimalB;
return Integer.toBinaryString(sum);
}
}
/*
Thought:
Use binary property, add all and move carry-on
String to charArray
*/
public class Solution {
public String addBinary(String a, String b) {
if (a == null || b == null || a.length() == 0 || b.length() == 0) {
return null;
}
char[] shortArr = a.length() < b.length() ? a.toCharArray() : b.toCharArray();
char[] longArr = a.length() < b.length() ? b.toCharArray() : a.toCharArray();
int carry = 0;
int shortVal = 0;
int nextCarry = 0;
int diff = longArr.length - shortArr.length;
for (int i = longArr.length - 1; i >= 0; i--) {
shortVal = (i - diff) >= 0 ? shortArr[i - diff] - '0': 0;
nextCarry = (longArr[i] - '0' + shortVal + carry) / 2;
longArr[i] =(char)((longArr[i] - '0' + shortVal + carry) % 2 + '0');
carry = nextCarry;
}
if (carry != 0) {
return "1" + new String(longArr);
}
return new String(longArr);
}
}
```
Morty Proxy This is a proxified and sanitized view of the page, visit original site.