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(); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/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 / ...
摘要:模拟加法复杂度时间空间思路模拟加法的运算法则,从最低位加到最高位。记得使用来减少字符串操作的开销。代码后续如果不是二进制相加,而是十六进制相加呢只要把算法中的除和余换成,并添加相应的十六进制字母就行了。 Add Binary Given two binary strings, return their sum (also a binary string). For example, ...
摘要:,,这道题就是求两个表示为字符串形式的二进制数字的和。最初我的想法是直接对两个字符串相对应的位进行直接运算,再用一个变量来表示进位,这里我选择将较短的字符串前面用补位,以获得两个相同长度的字符串进行逐位运算。 Given two binary strings, return their sum (also a binary string).For example,a = 11,b = ...
摘要:给定两个二进制字符串,返回他们的和用二进制表示。返回的数值是以开头,表明返回的数值是二进制函数用于将一个字符串或数字转换为整型。指定为非十进制时,需以字符串形式传入从第三个元素开始截取,忽略 (python、java)Given two binary strings, return their sum (also a binary string).The input strings a...
摘要:给定两个二进制字符串,返回他们的和用二进制表示。返回的数值是以开头,表明返回的数值是二进制函数用于将一个字符串或数字转换为整型。指定为非十进制时,需以字符串形式传入从第三个元素开始截取,忽略 (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
阅读 1314·2021-08-31 09:38
阅读 3142·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