Problem
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"
//using StringBuilder.insert(0, "content") is silly //just reverse and convert to string class Solution { public String addBinary(String a, String b) { int i = a.length()-1, j = b.length()-1, carry = 0; StringBuilder sb = new StringBuilder(); 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 != 0) sb.append(carry); return sb.reverse().toString(); } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/77047.html
Problem Given a binary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / ...
摘要:模擬加法復(fù)雜度時(shí)間空間思路模擬加法的運(yùn)算法則,從最低位加到最高位。記得使用來(lái)減少字符串操作的開(kāi)銷。代碼后續(xù)如果不是二進(jìn)制相加,而是十六進(jìn)制相加呢只要把算法中的除和余換成,并添加相應(yīng)的十六進(jìn)制字母就行了。 Add Binary Given two binary strings, return their sum (also a binary string). For example, ...
摘要:,,這道題就是求兩個(gè)表示為字符串形式的二進(jìn)制數(shù)字的和。最初我的想法是直接對(duì)兩個(gè)字符串相對(duì)應(yīng)的位進(jìn)行直接運(yùn)算,再用一個(gè)變量來(lái)表示進(jìn)位,這里我選擇將較短的字符串前面用補(bǔ)位,以獲得兩個(gè)相同長(zhǎng)度的字符串進(jìn)行逐位運(yùn)算。 Given two binary strings, return their sum (also a binary string).For example,a = 11,b = ...
摘要:給定兩個(gè)二進(jìn)制字符串,返回他們的和用二進(jìn)制表示。返回的數(shù)值是以開(kāi)頭,表明返回的數(shù)值是二進(jìn)制函數(shù)用于將一個(gè)字符串或數(shù)字轉(zhuǎn)換為整型。指定為非十進(jìn)制時(shí),需以字符串形式傳入從第三個(gè)元素開(kāi)始截取,忽略 (python、java)Given two binary strings, return their sum (also a binary string).The input strings a...
摘要:給定兩個(gè)二進(jìn)制字符串,返回他們的和用二進(jìn)制表示。返回的數(shù)值是以開(kāi)頭,表明返回的數(shù)值是二進(jìn)制函數(shù)用于將一個(gè)字符串或數(shù)字轉(zhuǎn)換為整型。指定為非十進(jìn)制時(shí),需以字符串形式傳入從第三個(gè)元素開(kāi)始截取,忽略 (python、java)Given two binary strings, return their sum (also a binary string).The input strings a...
閱讀 1074·2021-11-16 11:45
閱讀 2708·2021-09-27 13:59
閱讀 1315·2021-08-31 09:38
閱讀 3143·2019-08-30 15:52
閱讀 1315·2019-08-29 13:46
閱讀 2085·2019-08-29 11:23
閱讀 1631·2019-08-26 13:47
閱讀 2476·2019-08-26 11:54