AddBinary

二进制加法

输入2个字符串,字符串内由0和1组成;计算二者之和,返回字符串

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 package com.rust.TestString;

 public class AddBinary {
     public static String addBinary(String a, String b) {
         int alen = a.length() - 1;
         int blen = b.length() - 1;
         int carry = 0;
         String res = "";
         while (alen >=0 || blen >= 0 || carry == 1){
             int delta = (alen < 0)? 0 : a.charAt(alen--) - '0';/* 得到int */
             int beta = (blen < 0)? 0 : b.charAt(blen--) - '0';
             res = (char)('0' + delta ^ beta ^ carry) + res;/* 异或处理得到当前位 */
             carry = (delta + beta + carry) >> 1;/* 移位处理得到进位 */
         }
         return res;
     }

     public static void main(String args[]){
         String text = "0101010";
         String atext =    "111";
         String btext =    "010";
         System.out.println(addBinary(atext, text));
         System.out.println(addBinary(atext, btext));
         System.out.println(addBinary(btext, text));
     }
 }

输出:

0110001
1001
0101100

上一篇:《Java程序设计》第八周学习总结


下一篇:knockout 与checkbox联动