首页 > 其他 > 详细

[leetcode] Add Binary

时间:2014-07-09 23:51:46      阅读:489      评论:0      收藏:0      [点我收藏+]

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

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

https://oj.leetcode.com/problems/add-binary/

 

思路:类似大数计算只是进位有区别,小心carry的处理。

bubuko.com,布布扣
public class Solution {
    public String addBinary(String a, String b) {
        if (a == null || a.length() == 0)
            return b;
        if (b == null || b.length() == 0)
            return a;

        int m = a.length(), n = b.length();
        StringBuilder res = new StringBuilder();
        int i = m - 1, j = n - 1;
        int x, y, c = 0;
        while (i >= 0 || j >= 0) {
            x = (i >= 0) ? a.charAt(i) - ‘0‘ : 0;
            y = (j >= 0) ? b.charAt(j) - ‘0‘ : 0;
            res.append(x ^ y ^ c);
            c = (x + y + c >= 2) ? 1 : 0;
            i--;
            j--;
        }
        if (c == 1)
            res.append(1);

        return res.reverse().toString();

    }

    public static void main(String[] args) {
        System.out.println(new Solution().addBinary("11", "1"));
        System.out.println(new Solution().addBinary("1111", "1111"));
        System.out.println(new Solution().addBinary("11", ""));
        System.out.println(new Solution().addBinary("11111111111111111111", "1"));
        System.out.println(new Solution().addBinary("0101", "1010"));

    }
}
View Code

 

 

[leetcode] Add Binary,布布扣,bubuko.com

[leetcode] Add Binary

原文:http://www.cnblogs.com/jdflyfly/p/3812561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!