【LeetCode-面試演算法經典-Java實現】【067-Add Binary(二進位加法)】

來源:互聯網
上載者:User

標籤:二進位   演算法   面試   加法   java   

【067-Add Binary(二進位加法)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題

  Given two binary strings, return their sum (also a binary string).
  For example,
  a = "11"
  b = "1"
  Return "100"

題目大意

  給定兩個二進位的字串,返回它們的和,也是二進行制字串。

解題思路

  先將對應的兩個二進位字串轉換成對應的整數數組,從低位到高位進行相加,同時要考慮到最後相加還要擴充一位的情況。詳情請見代碼實現。

代碼實現

演算法實作類別

public class Solution {    public String addBinary(String a, String b) {        int[] ca = new int[a.length()];        int[] cb = new int[b.length()];        // 將字元數組中的值轉換了數值的0或者1        for (int i = 0; i < a.length(); i++) {            ca[i] = a.charAt(i) - ‘0‘;        }        // 將字元數組中的值轉換了數值的0或者1        for (int i = 0; i < b.length(); i++) {            cb[i] = b.charAt(i) - ‘0‘;        }        // 使用ca儲存的長度長        if (ca.length < cb.length) {            int[] tmp = ca;            ca = cb;            cb = tmp;        }        int ai = ca.length - 1; // 字元數組ca最後一個索引下標        int bi = cb.length - 1; // 字元數組cb最後一個索引下標        int carry = 0; // 下位的進位標識        int result; // 載入的結果        // 計算比如:1010101101 + 10100        while (ai >= 0 && bi >= 0) {            result = ca[ai] + cb[bi] + carry;            ca[ai] = result % 2;            carry = result / 2;            ai--;            bi--;        }        // 處理餘下的數字        while (ai >= 0) {            result = ca[ai] + carry;            ca[ai] = result % 2;            carry = result / 2;            if (carry == 0) {                break;            }            ai--;        }        // 將字元數組中的值轉換了字元的0或者1        for (int i = 0; i < ca.length; i++) {            ca[i] += ‘0‘;        }        // 不需要擴充一位        if (carry == 0) {            char[] ch = new char[ca.length];            for (int i = 0; i < ca.length; i++) {                ch[i] = (char) (ca[i]);            }            return new String(ch);        }         // 需要擴充一位        else {            char[] ch = new char[ca.length + 1];            ch[0] = ‘1‘;            for (int i = 0; i < ca.length; i++) {                ch[i + 1] = (char) (ca[i]);            }            return new String(ch);        }    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47203323】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【067-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.