leetcode : Add Bianry 基本功 字符转整数

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

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

 

tag: 字符asc码 。字符和数字加减法 。 '1' - '0' = 1 .  '1' - 0 != 0

 

public class Solution {
    public String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        if(a == null && b == null) {
            return result.toString();
        }
        if(a == null) {
            return b;
        }
        if(b == null) {
            return a;
        }
        int aIndex = a.length() - 1;
        int bIndex = b.length() - 1;
        int carry = 0;
        
        while(aIndex >= 0 && bIndex >= 0) {
            int sum = (int)((a.charAt(aIndex) - '0') + (b.charAt(bIndex) - '0') + carry ) % 2;
            carry = (int)((a.charAt(aIndex) - '0') + (b.charAt(bIndex) - '0') + carry ) / 2;
            result.append(sum);
            aIndex--;
            bIndex--;
        }
        
        while(aIndex >= 0){
            int sum = (int)((a.charAt(aIndex) - '0') + carry ) % 2;
            carry = (int)((a.charAt(aIndex) - '0') + carry) / 2;
            result.append(sum);
            aIndex--;
        }
        
         while(bIndex >= 0){
            int sum = (int)((b.charAt(bIndex) - '0') + carry ) % 2;
            carry = (int)((b.charAt(bIndex) - '0') + carry) / 2;
            result.append(sum);
            bIndex--;
        }
        
        if(carry == 1) {
            result.append("1");
        } 
        
        return result.reverse().toString();
        
        
    }
}

  

posted @ 2017-02-28 19:49  notesbuddy  阅读(237)  评论(0编辑  收藏  举报