• 67. Add Binary


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

    The input strings are both non-empty and contains only characters 1 or 0.

    Example 1:

    Input: a = "11", b = "1"
    Output: "100"

    Example 2:

    Input: a = "1010", b = "1011"
    Output: "10101"

    注意进位。
    solution1:
    class Solution {
        public String addBinary(String a, String b) {
            int carry = 0;
            int aDigit = 0;
            int bDigit = 0;
            StringBuilder result = new StringBuilder();
            
            for(int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >=0; i--, j--) {
                aDigit = (i > -1) ? a.charAt(i) - '0' : 0;
                bDigit = (j > -1) ? b.charAt(j) - '0' : 0;
                
                result.append((carry + aDigit + bDigit) % 2);                   // Appends String rep of int argument
                carry = (carry + aDigit + bDigit) / 2;
            }
            
            if(carry > 0) {
                result.append(carry);
            }
            
            return result.reverse().toString();
            
        }
    }
    

      It's just like in Add TwoNumbers, we add from the last digits of two numbers and keep update carry.

    Remember to care the last carry digit.

    Then reverse and return.

  • 相关阅读:
    详解扩展欧几里得算法(扩展GCD)
    NOIP 2012 同余方程
    NOIP 2011 观光公交
    NKOJ4330 逛公园
    NKOJ 7.7练习题A IP地址
    NKOJ3777 卡牌操作
    NKOJ3772 看电影
    NKOJ3765 k个最小和
    NKOJ3775 数列操作
    NKOJ3768 数列操作
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10166689.html
Copyright © 2020-2023  润新知