加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[leetcode]67.Add Binary

发布时间:2020-12-14 04:21:28 所属栏目:大数据 来源:网络整理
导读:题目 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" Outpu

题目

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"

解法

思路

用两个指针分别指向a和b的末尾,将a和b最后一位分别转为数字,用carry来保存要进位的数字,初始为0。如果a和b相加结束后,carry为1,则在sb之后加一个1,最后将sb逆转就可得到最终的结果,当然,这里也是可以用栈来代替reverse()的。

代码

class Solution {
    public String addBinary(String a,String b) {
        StringBuilder sb = new StringBuilder();
        int i = a.length() - 1;
        int 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‘;
            sb.append(sum % 2);
            carry = sum / 2;
        }
        if(carry == 1) sb.append(carry);
        return sb.reverse().toString();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读