标签:
二进制加法
输入2个字符串,字符串内由0和1组成;计算二者之和,返回字符串
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
1 package com.rust.TestString; 2 3 public class AddBinary { 4 public static String addBinary(String a, String b) { 5 int alen = a.length() - 1; 6 int blen = b.length() - 1; 7 int carry = 0; 8 String res = ""; 9 while (alen >=0 || blen >= 0 || carry == 1){ 10 int delta = (alen < 0)? 0 : a.charAt(alen--) - ‘0‘;/* 得到int */ 11 int beta = (blen < 0)? 0 : b.charAt(blen--) - ‘0‘; 12 res = (char)(‘0‘ + delta ^ beta ^ carry) + res;/* 异或处理得到当前位 */ 13 carry = (delta + beta + carry) >> 1;/* 移位处理得到进位 */ 14 } 15 return res; 16 } 17 18 public static void main(String args[]){ 19 String text = "0101010"; 20 String atext = "111"; 21 String btext = "010"; 22 System.out.println(addBinary(atext, text)); 23 System.out.println(addBinary(atext, btext)); 24 System.out.println(addBinary(btext, text)); 25 } 26 }
输出:
0110001
1001
0101100
标签:
原文地址:http://www.cnblogs.com/rustfisher/p/4896273.html