其他分享
首页 > 其他分享> > 蓝桥杯_二进制求和_力扣

蓝桥杯_二进制求和_力扣

作者:互联网

67. 二进制求和

给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。

示例 1:

输入: a = “11”, b = “1”
输出: “100”

示例 2:

输入: a = “1010”, b = “1011”
输出: “10101”

记录题解

import java.math.BigInteger;

public class AddBinary{
    public static void main(String[] args) {
        Solution solution = new AddBinary().new Solution();
        String a = "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101";
        String b = "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011";
        System.out.println(solution.addBinary(a,b));
    }

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public String addBinary(String a, String b) {
        BigInteger x = new BigInteger(a);
        BigInteger y = new BigInteger(b);
        if ("0".equals(x) && "0".equals(y)) return "0";
        char[] sum = String.valueOf(x.add(y)).toCharArray();
        int length = sum.length;

        boolean flag = false;
        for (int i = length-1; i >= 0 ; i--) {
            if (sum[i] > '2'){
                sum[i] = '1';
                if (i-1 >= 0) {
                    sum[i-1] += 1;
                }else {
                    flag = true;
                }
            }

            if (sum[i] == '2'){
                sum[i] = '0';
                if (i-1 >= 0) {
                    sum[i-1] += 1;
                }else {
                    flag = true;
                }
            }
        }

        if (flag){
            char[] ans = new char[length+1];
            ans[0] = '1';
            for (int i = 0; i < length; i++) {
                ans[i+1] = sum[i];
            }
            return String.valueOf(ans);
        }else {

            return String.valueOf(sum);
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}

力扣精选题解

class Solution {
    public String addBinary(String a, String b) {
        StringBuffer ans = new StringBuffer();

        int n = Math.max(a.length(), b.length()), carry = 0;
        for (int i = 0; i < n; ++i) {
            carry += i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0;
            carry += i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0;
            ans.append((char) (carry % 2 + '0'));
            carry /= 2;
        }

        if (carry > 0) {
            ans.append('1');
        }
        ans.reverse();

        return ans.toString();
    }
}

标签:力扣,String,二进制,sum,蓝桥,length,ans,carry,new
来源: https://blog.csdn.net/seabirdssss/article/details/123596415