LeetCode-Easy刷题(14) Add Binary

Posted 当以乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Easy刷题(14) Add Binary相关的知识,希望对你有一定的参考价值。

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

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


二进制字符串相加返回结果字符串
 //维护一个进位指针
    public static String addBinary(String a, String b) 

        if(a==null || a.length()<1)
            return b;
        

        if(b ==null || b.length()<1)
            return a;
        

        int nextLocal = 0;

        int i = a.length()-1;
        int j = b.length()-1;

        StringBuffer sb = new StringBuffer();

        while(i>=0 && j>=0)//按位置相加到一个加完

            //该位置相加
            int result = (int)(a.charAt(i) - '0' + b.charAt(j) - '0') + nextLocal;
            nextLocal = result/2;//进位判断
            int current = result%2;//当前位置结果
            sb.append(current);
            i--;
            j--;
        

        while(i>=0)
            int result = (int)(a.charAt(i) -'0') +nextLocal;
            nextLocal = result/2;//进位判断
            int current = result%2;//当前位置结果
            sb.append(current);
            i--;
        

        while(j>=0)
            int result = (int)(b.charAt(j) -'0') +nextLocal;
            nextLocal = result/2;//进位判断
            int current = result%2;//当前位置结果
            sb.append(current);
            j--;
        
        //最后的进位判断
        if(nextLocal!=0)
            sb.append(nextLocal);
        

        return sb.reverse().toString();
    


以上是关于LeetCode-Easy刷题(14) Add Binary的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Easy刷题(31) Single Number

LeetCode-Easy刷题 Remove Element

LeetCode-Easy刷题(19) Same Tree

LeetCode-Easy刷题(33) Min Stack

LeetCode-Easy刷题(33) Min Stack

LeetCode-Easy刷题(26) Path Sum