Add Binary

原创 2015年11月19日 21:14:59

题目描述

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

题目解答

解题思路

二进制加法都是从低位开始加(也就是字符串的高位),所以要从高位开始加

‘1’ - ‘0’ = 1

代码实现

/**
 * 从低位开始加   也就是字符串的高位
 */
public class Solution {
    public String addBinary(String a, String b) {
         if(a == null || b == null)
            return "";

        StringBuilder ret = new StringBuilder("");
        int i = a.length()-1, 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');

            carry = sum / 2;
            //int + char --> int 注意
            char temp = (char)(sum%2 + '0');
            ret.insert(0, temp);
        }
        if(carry == 1)
            ret.insert(0, '1');
        return ret.toString();
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 题目之4 Add Binary

题目: Given two binary strings, return their sum (also a binary string). For example, a = "11" b ...

Leetcode - Add Binary

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

LeetCode题解:Add Binary

题目链接:Add Binary 题目描述: Given two binary strings, return their sum (also a binary string). For e...
  • yums467
  • yums467
  • 2015年09月08日 08:27
  • 256

LeetCode 067 Add Binary

题目 Given two binary strings, return their sum (also a binary string). For example,...
  • seawade
  • seawade
  • 2014年02月16日 09:22
  • 462

LeetCode笔记:67. Add Binary

模拟两个字符串二进制数的加法

Add Binary - LeetCode 67

题目描述:Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "...
  • bu_min
  • bu_min
  • 2015年04月24日 22:05
  • 259

Python学习——leetcode(Add Binary)

Add Binary: Given two binary strings, return their sum (also a binary string). For example, a = "11"...

Leetcode9: Add Binary

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

LeetCode Add Binary

Description: Given two binary strings, return their sum (also a binary string). Solution: 将十进制的...

[Leetcode]Add Binary

Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Add Binary
举报原因:
原因补充:

(最多只允许输入30个字)