Share my Java solution.


  • 0
    F
    public class Solution {
        public String addBinary(String a, String b) {
            char[] longArray = (a.length() > b.length()) ? a.toCharArray() : b.toCharArray();
            char[] shortArray = (a.length() > b.length()) ? b.toCharArray() : a.toCharArray();
            boolean plusOne = false;
            
            for(int i = 1; i <= longArray.length; i++) {
                if (shortArray.length < i && !plusOne) {
                    break;
                }
                int count = 0;
                if( shortArray.length >= i && shortArray[shortArray.length - i] == '1') { count++;}
                if( longArray[longArray.length - i] == '1') { count++; }
                if(plusOne) { count++; }
                
                plusOne = count >= 2; 
                longArray[longArray.length - i] = count%2 == 0 ? '0' : '1';
            }
            
            return (plusOne) ? "1" + String.valueOf(longArray) : String.valueOf(longArray);
        }
    }
    

    No need to iterate the long string if no carrier and finish parsing the short string.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.