67. Add Binary
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){ int sum = 0; sum += carry; if( i >= 0){ sum += a.charAt(i) - '0'; i--; } if( j >= 0){ sum += b.charAt(j) - '0'; j--; } sb.append(sum % 2); carry = sum / 2; } if( carry == 1){ sb.append(carry); } return sb.reverse().toString(); } } //// a.charAt(i) - '0' ///// sb.append() ////// sb.reverse().toString();
this one is two strings added together. Still need to add the
Two element from two string from the last digit
Use a string builder to add backwards, by that, I mean,
Use append to append the new element, so its reverse order
Use while outside when the two numbers are not exhausted
And use two ifs to check if number a and number b
Are not exhausted, and add the current digit if valid
Append the sum % 2
And carry = sum / 2
An carray is added to the next level sum
11 + 1 = 100
When the 11 and 1 length are all exhausted, we check if the carry is 1 , carry can only be 1 or 0, if carry is 1, then we know we need to append 1 , if its 0, we don’t need to do anything
This is similar to plus one that problem,
At the end, we need to reverse the string , since we append the sum at the tail
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"
posted on 2018-07-18 09:44 猪猪🐷 阅读(104) 评论(0) 收藏 举报
浙公网安备 33010602011771号