zoukankan      html  css  js  c++  java
  • Add Binary

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

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

    StringBuilder +  reverse method

    public class Solution {
        public String addBinary(String a, String b) {
            if(a == null || a.equals("")) return b;
            if(b == null || b.equals("")) return a;
            
            StringBuilder a1 = new StringBuilder(a);
            a1.reverse();
            StringBuilder b1 = new StringBuilder(b);
            b1.reverse();
            
            StringBuilder result = new StringBuilder();
            int len = Math.max(a.length(), b.length());
            int carry = 0;
            for(int i = 0; i < len ; i++){
                int t1 = (i >= a.length()? 0 : (a1.charAt(i) - '0'));
                int t2 = (i >= b.length()? 0 : (b1.charAt(i) - '0'));
                int t3 = t1+t2+carry;
                carry = t3/2;
                t3 = t3%2;
                result.append(t3);
            }
            
            if(carry != 0){
                result.append(carry);
            }
            
            result.reverse();
            return result.toString();
        }
    }
  • 相关阅读:
    Python(多进程multiprocessing模块)
    Python(队列)
    Unique Paths
    Unique Paths
    Jump Game II
    Jump Game
    Path Sum II
    Path Sum
    Remove Element
    Implement strStr()
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3536710.html
Copyright © 2011-2022 走看看