TypechoJoeTheme

IT技术分享

统计

[LeetCode 67] Add Binary [Java]

2018-02-18
/
0 评论
/
846 阅读
/
正在检测是否收录...
02/18

1. Description

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

2. Example

a = "11"
b = "1"
Return "100".

3.Code

public class LeetCode0067 {

    public String addBinary(String a, String b) {
        if (a == null || b == null) {
            return null;
        }

        if (a.length() == 0) {
            return b;
        } else if (b.length() == 0) {
            return a;
        }

        StringBuilder sb = new StringBuilder();
        int carry = 0, aInt = 0, bInt = 0;

        for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i--, j--) {

            aInt = i < 0 ? 0 : a.charAt(i) - '0';
            bInt = j < 0 ? 0 : b.charAt(j) - '0';

            sb.append(aInt ^ bInt ^ carry);
            carry = aInt + bInt + carry > 1 ? 1 : 0;
        }

        if (carry != 0) {
            sb.append(carry);
        }

        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        LeetCode0067 leetcode = new LeetCode0067();
        System.out.println(leetcode.addBinary("11", "1"));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1446/(转载时请注明本文出处及文章链接)