67. Add Binary

栏目: Java · 发布时间: 6年前

内容简介: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.难度: easy

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"

难度: easy

题目:

给定两个二进制字符串,返回它们的和(也是二进制字符串)。

字符串都不为空且只有0、1组成。

Runtime: 2 ms, faster than 95.70% of Java online submissions for Add Binary.

Memory Usage: 26.2 MB, less than 54.54% of Java online submissions for Add Binary.

public class Solution {
    public String addBinary(String a, String b) {
        int i = a.length() - 1, j = b.length() - 1, carry = 0;
        StringBuilder result = new StringBuilder();
        while (i >= 0 || j >= 0) {
            char ac = i >= 0 ? a.charAt(i) : '0';
            char bc = j >= 0 ? b.charAt(j) : '0';
            
            int sum = (ac - '0') + (bc - '0') + carry;
            result.append(sum % 2);
            carry = sum / 2;
            i--;
            j--;
        }
        
        if (carry > 0) {
            result.append(1);
        }
        
        return new String(result.reverse());
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

精通正则表达式

精通正则表达式

[美] Jeffrey E.F.Friedl / 余晟 / 电子工业出版社 / 2012-7 / 89.00元

《精通正则表达式(第3版)》内容简介:随着互联网的迅速发展,几乎所有工具软件和程序语言都支持的正则表达式也变得越来越强大和易于使用。《精通正则表达式(第3版)》是讲解正则表达式的经典之作。《精通正则表达式(第3版)》主要讲解了正则表达式的特性和流派、匹配原理、优化原则、实用诀窍以及调校措施,并详细介绍了正则表达式在Perl、Java、.NET、PHP中的用法。《精通正则表达式(第3版)》自第1版开......一起来看看 《精通正则表达式》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试