• [leetcode]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"

    注意:

    StringBuilder.insert(int offset,  char c) 表示将char放入offset这个偏移量

    Character.forDigit(int digit, int radix) 返回radix进制下,该digit所代表的char

    代码

     1 class Solution {
     2     public String addBinary(String a, String b) {
     3         StringBuilder sb = new StringBuilder(); // new a StringBuilder because it will be easy to append
     4         
     5         char[] arrayA = a.toCharArray();// convert char to array 
     6         char[] arrayB = b.toCharArray();// convert char to array
     7         
     8         int i = a.length()-1; 
     9         int j = b.length()-1; 
    10         int carry = 0; 
    11         
    12         while(i>=0 || j>=0 || carry >0){  
    13             int updateA = i>=0 ? arrayA[i--]-'0':0; 
    14             int updateB = j>=0 ? arrayB[j--]-'0':0; 
    15             int sum = updateA + updateB + carry; 
    16             sb.insert(0, Character.forDigit(sum%2, 10)); // I convert this sum to binary then insert to sb
    17             carry = sum/2; // coz it is binary, carry would be sum/2
    18         } 
    19         return sb.toString();  //  convert StringBuilder to String
    20     }
    21 }
  • 相关阅读:
    【BZOJ1396】识别子串
    【BZOJ3309】DZY Loves Math
    【XSY3306】alpha
    整体二分
    常系数齐次线性递推
    【XSY2968】线性代数
    【XSY2892】【GDSOI2018】谁是冠军
    【BZOJ5020】[LOJ2289]【THUWC2017】在美妙的数学王国中畅游
    【XSY2989】字符串
    【XSY2988】取石子
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9808258.html
Copyright © 2020-2023  润新知