码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Add Binary

时间:2014-07-09 23:52:48      阅读:383      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   art   

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

标签:style   blog   http   color   os   art   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!