资讯专栏INFORMATION COLUMN

[LeetCode] Add Binary

sean / 2134人阅读

Problem

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Solution
//using StringBuilder.insert(0, "content") is silly
//just reverse and convert to string

class Solution {
    public String addBinary(String a, String b) {
        int i = a.length()-1, j = b.length()-1, carry = 0;
        StringBuilder sb = new StringBuilder();
        while (i >= 0 || j >= 0) {
            int sum = carry;
            if (i >= 0) sum += a.charAt(i--)-"0";
            if (j >= 0) sum += b.charAt(j--)-"0";
            sb.append(sum%2);
            carry = sum/2;
        }
        if (carry != 0) sb.append(carry);
        return sb.reverse().toString();
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77047.html

相关文章

  • [LintCode/LeetCode] Binary Tree Level Order Traver

    Problem Given a binary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / ...

    makeFoxPlay 评论0 收藏0
  • [Leetcode] Add Binary 二进制相加

    摘要:模拟加法复杂度时间空间思路模拟加法的运算法则,从最低位加到最高位。记得使用来减少字符串操作的开销。代码后续如果不是二进制相加,而是十六进制相加呢只要把算法中的除和余换成,并添加相应的十六进制字母就行了。 Add Binary Given two binary strings, return their sum (also a binary string). For example, ...

    lk20150415 评论0 收藏0
  • leetcode_67 Add Binary

    摘要:,,这道题就是求两个表示为字符串形式的二进制数字的和。最初我的想法是直接对两个字符串相对应的位进行直接运算,再用一个变量来表示进位,这里我选择将较短的字符串前面用补位,以获得两个相同长度的字符串进行逐位运算。 Given two binary strings, return their sum (also a binary string).For example,a = 11,b = ...

    codeGoogle 评论0 收藏0
  • Leetcode 67:Add Binary(二进制求和)

    摘要:给定两个二进制字符串,返回他们的和用二进制表示。返回的数值是以开头,表明返回的数值是二进制函数用于将一个字符串或数字转换为整型。指定为非十进制时,需以字符串形式传入从第三个元素开始截取,忽略 (python、java)Given two binary strings, return their sum (also a binary string).The input strings a...

    chenjiang3 评论0 收藏0
  • Leetcode 67:Add Binary(二进制求和)

    摘要:给定两个二进制字符串,返回他们的和用二进制表示。返回的数值是以开头,表明返回的数值是二进制函数用于将一个字符串或数字转换为整型。指定为非十进制时,需以字符串形式传入从第三个元素开始截取,忽略 (python、java)Given two binary strings, return their sum (also a binary string).The input strings a...

    sf190404 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<