• *Add Binary


    Given two binary strings, return their sum (also a binary string).
    For example,
    a = "11"
    b = "1"
    Return "100".
     
     
     
     1     public String addBinary(String a, String b) {
     2         if (a==null ||a.length()==0){
     3             return b;
     4         }
     5         
     6         if (b==null || b.length()==0){
     7             return a;
     8         }
     9         
    10        StringBuilder sb=new StringBuilder();
    11        
    12         
    13         int lastA=a.length()-1;
    14         int lastB=b.length()-1;
    15         int carry=0;
    16         
    17         
    18         while (lastA>=0 ||lastB>=0 ||carry>0){
    19             int num1=lastA>=0?a.charAt(lastA--)-'0':0;
    20             int num2=lastB>=0?b.charAt(lastB--)-'0':0;
    21             int current=(num1+num2+carry)%2;
    22             carry=(num1+num2+carry)/2;
    23             
    24             sb.insert(0, current);
    25             
    26             
    27         }
    28         
    29         return sb.toString();
    30     }
     
    reference: http://rleetcode.blogspot.com/2014/02/add-binary-java.html
  • 相关阅读:
    Day11作业
    day12作业
    samba共享服务
    PHP7 redis扩展安装
    linux lin命令
    PhpStorm,Pycharm,Goland破解
    PHP规范PSR2
    PHP 过滤器(Filter)
    Linux下Redis的安装与配置
    linux命令汇总
  • 原文地址:https://www.cnblogs.com/hygeia/p/4799856.html
Copyright © 2020-2023  润新知