zoukankan      html  css  js  c++  java
  • [Leetcode] Add Binary

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

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

    Solution:

     1 public class Solution {
     2     public String addBinary(String a, String b) {
     3         if(a==null)
     4             return b;
     5         if(b==null)
     6             return a;
     7         int end_a=a.length()-1;
     8         int end_b=b.length()-1;
     9         int carry=0;
    10         String result="";
    11         while(end_a>=0&&end_b>=0){
    12             int temp=(a.charAt(end_a)-'0')+(b.charAt(end_b)-'0')+carry;
    13             carry=temp/2;
    14             temp%=2;
    15             result=(temp+"")+result;
    16             end_a--;
    17             end_b--;
    18         }
    19         while(end_a>=0){
    20             int temp=(a.charAt(end_a)-'0')+carry;
    21             carry=temp/2;
    22             temp%=2;
    23             result=(temp+"")+result;
    24             end_a--;
    25         }
    26         while(end_b>=0){
    27             int temp=(b.charAt(end_b)-'0')+carry;
    28             carry=temp/2;
    29             temp%=2;
    30             result=(temp+"")+result;
    31             end_b--;
    32         }
    33         if(carry!=0){
    34             result=(carry+"")+result;
    35         }
    36         return result;
    37     }
    38 }
  • 相关阅读:
    git
    composer
    laravel saas
    算法模板-01背包
    GMP-C/C++(大数库)使用方法
    算法模板-容斥原理
    算法模板-欧拉函数
    算法模板-素数判断/素数筛法
    算法模板-质因数分解
    算法模板-快速幂取模
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4110962.html
Copyright © 2011-2022 走看看