|
1 | 1 | package com.fishercoder.solutions; |
2 | 2 |
|
3 | | -/** |
4 | | - * 67. Add Binary |
5 | | - * |
6 | | - * Given two binary strings, return their sum (also a binary string). |
7 | | - * For example, |
8 | | - * a = "11" |
9 | | - * b = "1" |
10 | | - * Return "100". |
11 | | - */ |
12 | | - |
13 | 3 | public class _67 { |
14 | | - public static class Solution1 { |
15 | | - /** |
16 | | - * credit: https://discuss.leetcode.com/topic/13698/short-ac-solution-in-java-with-explanation |
17 | | - * 1. use StringBuilder.reverse() function! Nice! |
18 | | - * 2. if a numeric number is represented/stored in String, how to get its value: use Character.getNumericValue(s.charAt(i)) |
19 | | - * 3. directly adding/subtracting chars will end up working with their ASCII numbers, e.g. chars[0] = 'a', chars[1] = 'b', then chars[0] + chars[1] will become 195. |
20 | | - */ |
21 | | - public String addBinary(String a, String b) { |
22 | | - int carry = 0; |
23 | | - int i = a.length() - 1; |
24 | | - int j = b.length() - 1; |
25 | | - StringBuilder sb = new StringBuilder(); |
26 | | - while (i >= 0 || j >= 0) { |
27 | | - int sum = carry; |
28 | | - if (i >= 0) { |
29 | | - sum += a.charAt(i--) - '0'; |
30 | | - } |
31 | | - if (j >= 0) { |
32 | | - sum += b.charAt(j--) - '0'; |
| 4 | + public static class Solution1 { |
| 5 | + /** |
| 6 | + * credit: https://discuss.leetcode.com/topic/13698/short-ac-solution-in-java-with-explanation |
| 7 | + * 1. use StringBuilder.reverse() function! Nice! |
| 8 | + * 2. if a numeric number is represented/stored in String, how to get its value: use Character.getNumericValue(s.charAt(i)) |
| 9 | + * 3. directly adding/subtracting chars will end up working with their ASCII numbers, e.g. chars[0] = 'a', chars[1] = 'b', then chars[0] + chars[1] will become 195. |
| 10 | + */ |
| 11 | + public String addBinary(String a, String b) { |
| 12 | + int carry = 0; |
| 13 | + int i = a.length() - 1; |
| 14 | + int j = b.length() - 1; |
| 15 | + StringBuilder sb = new StringBuilder(); |
| 16 | + while (i >= 0 || j >= 0) { |
| 17 | + int sum = carry; |
| 18 | + if (i >= 0) { |
| 19 | + sum += a.charAt(i--) - '0'; |
| 20 | + } |
| 21 | + if (j >= 0) { |
| 22 | + sum += b.charAt(j--) - '0'; |
| 23 | + } |
| 24 | + sb.append(sum % 2); |
| 25 | + carry = sum / 2; |
| 26 | + } |
| 27 | + if (carry != 0) { |
| 28 | + sb.append(carry); |
| 29 | + } |
| 30 | + return sb.reverse().toString(); |
33 | 31 | } |
34 | | - sb.append(sum % 2); |
35 | | - carry = sum / 2; |
36 | | - } |
37 | | - if (carry != 0) { |
38 | | - sb.append(carry); |
39 | | - } |
40 | | - return sb.reverse().toString(); |
41 | 32 | } |
42 | | - } |
43 | 33 | } |
0 commit comments