Add Binary Leetcode java


題目

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 

題解

二進制加法都是從最低位(從右加到左)。所以對兩個字符串要從最后一位開始加,如果遇見長度不一的情況,就把短的字符串高位補0.

每輪計算要加上進位,最后跳出循環后要堅持進位是否為1,以便更新結果。

 

代碼如下(from discussion):

 

 1  public String addBinary(String a, String b) {
 2      int m = a.length();
 3      int n = b.length();
 4      int carry = 0;
 5     String res = "";
 6      //  the final length of the result depends on the bigger length between a and b, 
 7       //  (also the value of carry, if carry = 1, add "1" at the head of result, otherwise)
 8       int maxLen = Math.max(m, n);
 9      for ( int i = 0; i < maxLen; i++) {
10          //  start from last char of a and b
11           //  notice that left side is int and right side is char
12           //  so we need to  minus the decimal value of '0'
13           int p=0,q=0;
14          if(i<m)
15             p = a.charAt(m-1-i) - '0';
16          else
17             p = 0;
18         
19          if(i<n)
20             q = b.charAt(n-1-i)-'0';
21          else
22             q = 0;
23             
24          int tmp = p + q + carry;
25         carry = tmp / 2;
26         res += tmp % 2;
27     }
28      return (carry == 0) ? res : "1" + res;
29     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM