zoukankan      html  css  js  c++  java
  • 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"

    从后往前加,用两个参数,sum和remainder分别表示和、余数。当两个string数组下标不越界时,sum等于两个数相加,res append (sum % 2),余数为 sum/2,表示进位,下一次进入循环时,sum就等于remainder,在此基础上继续累加。最后当两个string都加完,考虑进位:如果最后的余数为0,不进位;如果不为0,在res里append最后一次循环得到的余数。

    由于append的顺序和二进制数的高低位顺序是相反的,最后还要把res反转一下

    time: O(n), space: O(n)

    class Solution {
        public String addBinary(String a, String b) {
            StringBuilder res = new StringBuilder();
            int i = a.length() - 1, j = b.length() - 1;
            int remainder = 0;
            while(i >= 0 || j >= 0) {
                int sum = remainder;
                if(i >= 0) {
                    sum += a.charAt(i--) - '0';
                }
                if(j >= 0) {
                    sum += b.charAt(j--) - '0';
                }
                res.append(sum % 2);
                remainder = sum / 2;
            }
            if(remainder != 0) {
                res.append(remainder);
            }
            return res.reverse().toString();
        }
    }
  • 相关阅读:
    RSA算法
    本地CodeForces
    基于Giolite 多人开发
    DES算法
    MD5算法
    仓库库存管理系统(C+MySQL+ODBC)
    Spring源码解析(一)开篇
    JDK动态代理实现源码分析
    J.U.C Atomic(一)CAS原理
    JDK 注解详解
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10117718.html
Copyright © 2011-2022 走看看