首页 > 代码库 > leetcode--Add Binary
leetcode--Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class Solution { /**The program is used to calculate the sum of two binaries. This is a fundamental problem.<br> * @param a --binary string as the first operand * @param b --binary string as the second operand * @return a string --the sum of binary a and b * @author Averill Zheng * @version 2014-06-03 * @since JDK 1.7 */ public String addBinary(String a, String b) { int lengthOfA = a.length(), lengthOfB = b.length(); StringBuffer resultBuffer = new StringBuffer(); int carry = 0 ; while (lengthOfA > 0 && lengthOfB > 0 ){ int sum = (a.charAt(lengthOfA - 1 ) - ‘0‘ ) + (b.charAt(lengthOfB - 1 )- ‘0‘ ) + carry; carry = sum / 2 ; resultBuffer.insert( 0 , sum % 2 ); --lengthOfA; --lengthOfB; } String remaining = (lengthOfA == 0 )? b : a; int index = (lengthOfA == 0 ) ? lengthOfB : lengthOfA; while (index > 0 ){ int sum = (remaining.charAt(index - 1 ) - ‘0‘ ) + carry; carry = sum / 2 ; resultBuffer.insert( 0 , sum % 2 ); --index; } if (carry != 0 ) resultBuffer.insert( 0 , 1 ); return resultBuffer.toString(); } } |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。