-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path067. Add Binary
107 lines (96 loc) · 2.65 KB
/
067. Add Binary
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* @lc app=leetcode id=66 lang=java
*
* [66] Plus One
*
* https://leetcode.com/problems/plus-one/description/
*
* algorithms
* Easy (40.46%)
* Total Accepted: 337.9K
* Total Submissions: 834.3K
* Testcase Example: '[1,2,3]'
*
* Given a non-empty array of digits representing a non-negative integer, plus
* one to the integer.
*
* The digits are stored such that the most significant digit is at the head of
* the list, and each element in the array contain a single digit.
*
* You may assume the integer does not contain any leading zero, except the
* number 0 itself.
*
* Example 1:
* Input: [1,2,3]
* Output: [1,2,4]
* Explanation: The array represents the integer 123.
*
* Example 2:
* Input: [4,3,2,1]
* Output: [4,3,2,2]
* Explanation: The array represents the integer 4321.
*
*/
// Java solution 01:
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while(i >= 0 || j >= 0) {
if(i >= 0) {
carry += a.charAt(i) - '0';
i--;
}
if(j >= 0) {
carry += b.charAt(j) - '0';
j--;
}
sb.insert(0, carry % 2);
carry = carry / 2;
}
if(carry > 0) {
sb.insert(0, carry);
}
return sb.toString();
}
}
// Java solution 02:
public class Solution {
public String addBinary(String a, String b) {
char arra[] = a.toCharArray();
char arrb[] = b.toCharArray();
int lena = a.length() - 1;
int lenb = b.length() - 1;
int lenre = Math.max(lena, lenb) + 1;
int result[] = new int[lenre+1];
int na, nb;
int carry = 0;
while(lena >= 0 || lenb >= 0){
na = 0;
nb = 0;
if(lena >= 0){
na = Integer.parseInt(String.valueOf(arra[lena]));
}
if(lenb >= 0){
nb = Integer.parseInt(String.valueOf(arrb[lenb]));
}
result[Math.max(lena, lenb)+1] = (na + nb + carry) % 2;
carry = (na + nb + carry) / 2;
lena--;
lenb--;
}
int index;
if(carry > 0){
result[0] = carry;
index = 0;
}
else{index = 1;}
StringBuilder string = new StringBuilder();
for(; index < result.length; index++){
string.append(result[index]);
}
return string.toString();
}
}