PisecesPeng / PisecesPeng.record.me

:beach_umbrella: All things are difficult before they are easy
MIT License
3 stars 1 forks source link

二进制求和 #31

Closed PisecesPeng closed 3 years ago

PisecesPeng commented 3 years ago

二进制求和

给定两个二进制字符串, 返回他们的和(用二进制表示).
输入为非空字符串且只包含数字10.

示例1:
输入: a = "11", b = "1"
输出: "100"

示例2:
输入: a = "1010", b = "1011"
输出: "10101"


题目地址: https://leetcode-cn.com/problems/add-binary/

PisecesPeng commented 3 years ago

解题思路

代码

public static String func(String a, String b) {
    int rTmp = Integer.valueOf(a).intValue() + Integer.valueOf(b).intValue();
    String result = "";
    boolean plusOne = false;  // '是否进位'状态
    while (rTmp > 0) {
        int r = rTmp % 10;  // 取得个位数
        // 判断当前个位数, 且判断'是否进位', 向前累加值, 并更新'是否进位'状态
        if (r == 0) {
            if (plusOne) result = "1" + result;
            else result = "0" + result;
            plusOne = false;
        } else if (r == 1) {
            if (plusOne) result = "0" + result;
            else result = "1" + result;
        } else {
            if (plusOne) result = "1" + result;
            else result = "0" + result;
            plusOne = true;
        }
        rTmp /= 10;
    }
    // 确认首位是否还需要进位
    if (plusOne) result = "1" + result;
    return result;
}
PisecesPeng commented 3 years ago

LeetCode题解

解题思路

代码

public static String func(String a, String b) {
    return Integer.toBinaryString(
        Integer.parseInt(a, 2) + Integer.parseInt(b, 2)
    );
}
PisecesPeng commented 3 years ago

LeetCode题解

解题思路

代码

public static String func(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();
}
PisecesPeng commented 3 years ago

LeetCode题解

解题思路