67. Add Binary

原创 2016年06月01日 18:41:49

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) {
         if(a.length() < b.length()){
            String tmp = a;
            a = b;
            b = tmp;
        }

        int pa = a.length()-1;
        int pb = b.length()-1;
        int carries = 0;
        String rst = "";

        while(pb >= 0){
            int sum = (int)(a.charAt(pa) - '0') + (int)(b.charAt(pb) - '0') + carries;
            rst = String.valueOf(sum % 2) + rst;
            carries = sum / 2;
            pa --;
            pb --;
        }

        while(pa >= 0){
            int sum = (int)(a.charAt(pa) - '0') + carries;
            rst = String.valueOf(sum % 2) + rst;
            carries = sum / 2;
            pa --;
        }       

        if (carries == 1)
            rst = "1" + rst;
        return rst;
    
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 67 — Add Binary(C++ Java Python)

题目:http://oj.leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a bi...

LeetCode(67) Add Binary

题目Given two binary strings, return their sum (also a binary string).For example, a = “11” b = “1” ...
  • fly_yr
  • fly_yr
  • 2015-08-19 20:58
  • 1630

67. Add Binary

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

LeetCode 67 Add Binary(二进制相加)(*)

翻译给定两个二进制字符串,返回它们的和(也是二进制字符串)。例如, a = "11" b = "1" 返回 "100".原文Given two binary strings, return their...
  • NoMasp
  • NoMasp
  • 2016-02-02 13:49
  • 1846

LeetCode-67 Add Binary(二进制数相加)

LeetCode-67 Add Binary(二进制数相加) Given two binary strings, return their sum (also a binary string). ...

LeetCode笔记:67. Add Binary

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

Add Binary - LeetCode 67

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

【Leetcode】67. Add Binary

思路: (1)先求a、b长度的较大值len。 (2)在a和b中较短的字符串前面补齐0。 (3)用flag记录每一位的进位,result记录求和结果。 (4)从后往前遍历a和b,让相应位相加并加上fla...

LeetCode 67. Add Binary(二进制加)

原题网址:https://leetcode.com/problems/add-binary/ Given two binary strings, return their sum (also a ...

LeetCode-67. Add Binary

问题描述Given two binary strings, return their sum (also a binary string). For example, a = “11” b = ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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