[leetcode]67.Add Binary

來源:互聯網
上載者:User

標籤:output   tco   rev   結束   bin   java   only   length   input   

題目

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"

解法思路

用兩個指標分別指向a和b的末尾,將a和b最後一位分別轉為數字,用carry來儲存要進位的數字,初始為0。如果a和b相加結束後,carry為1,則在sb之後加一個1,最後將sb逆轉就可得到最終的結果,當然,這裡也是可以用棧來代替reverse()的。

代碼
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 = carry;            if(i >= 0) sum += a.charAt(i--) - ‘0‘;            if(j >= 0) sum += b.charAt(j--) - ‘0‘;            sb.append(sum % 2);            carry = sum / 2;        }        if(carry == 1) sb.append(carry);        return sb.reverse().toString();    }}

[leetcode]67.Add Binary

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.