LeetCode-067-二進(jìn)制求和

二進(jìn)制求和

題目描述:給你兩個(gè)二進(jìn)制字符串,返回它們的和(用二進(jìn)制表示)。

輸入為 非空 字符串且只包含數(shù)字 1 和 0。

示例說(shuō)明請(qǐng)見(jiàn)LeetCode官網(wǎng)。

來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/add-binary/
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

解法一:分組處理

由于過(guò)長(zhǎng)的字符串直接轉(zhuǎn)成int值會(huì)報(bào)錯(cuò),因?yàn)槌隽薸nt值的上線,所以采取分段處理的方式,從后往前,每30位相加,利用了Integer.parseInt(String, 2)方法將字符串二進(jìn)制數(shù)轉(zhuǎn)成10進(jìn)制的int值,然后利用Integer.toBinaryString(int)方法將相加后的值再轉(zhuǎn)成二進(jìn)制字符串,然后把分段的字符串加起來(lái),就是最后的結(jié)果。

做的過(guò)程中有幾點(diǎn)要考慮:

  • 第一,每段相加時(shí),考慮是否有進(jìn)位,如果有進(jìn)位,用addOne表示進(jìn)位數(shù),值為1,在下一分段相加時(shí)把a(bǔ)ddOne加上;
  • 第二,當(dāng)每段相加的結(jié)果長(zhǎng)度小于30位時(shí),需要在前面補(bǔ)0,補(bǔ)到30位。
public class LeetCode_067 {
    public static String addBinary(String a, String b) {
        int addOne = 0;
        String result = "";
        while (a.length() > 30 || b.length() > 30) {
            String aStr;
            String bStr;
            if (a.length() > 30) {
                aStr = a.substring(a.length() - 30, a.length());
                a = a.substring(0, a.length() - 30);
            } else {
                aStr = a;
                a = "0";
            }
            if (b.length() > 30) {
                bStr = b.substring(b.length() - 30, b.length());
                b = b.substring(0, b.length() - 30);
            } else {
                bStr = b;
                b = "0";
            }
            String temp = Integer.toBinaryString(Integer.parseInt(aStr, 2) + Integer.parseInt(bStr, 2) + addOne);
            if (temp.length() > 30) {
                addOne = 1;
                temp = temp.substring(1, temp.length());
            } else {
                if(temp.length() < 30) {
                    int zeroCount = 30 - temp.length();
                    for(int i = 0; i < zeroCount; i++) {
                        temp = "0" + temp;
                    }
                }
                addOne = 0;
            }
            result = temp + result;
        }
        return Integer.toBinaryString(Integer.parseInt(a, 2) + Integer.parseInt(b, 2) + addOne) + result;
    }

    public static void main(String[] args) {
        String a = "1001101011011010000010111010100111001000100001111110011111001010100101111";
        String b = "111000011000010000001100001001010011000101000000001111101101000100000000100100001100010000111001000";
        System.out.println(addBinary(a, b));
    }
}

【每日寄語(yǔ)】 天可補(bǔ),??商睿仙娇梢?。日月既往,不可復(fù)追。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容