LeetCode(56)-Add Binary

时间:2022-07-10 05:47:06

题目:

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

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

思路:

  • 题意:对字符串的二进制数字,计算
  • 把二进制转化为整数,设置变量carry位进位,sum%2,是相应的数字,carry = sum/2

    -

代码:

public class Solution {
    public String addBinary(String a, String b) {
        if(a.length() < b.length()){
            String tmp = a;
            a = b;
            b = tmp;
        }
        int lengthA = a.length()-1;
        int lengthB = b.length()-1;
        int carry = 0;
        String all = "";
        while(lengthB >= 0){
            int num = (int)(a.charAt(lengthA)-'0')+(int)(b.charAt(lengthB)-'0')+carry;
            int k = num%2;
            carry = num/2;
            all = String.valueOf(k)+all;
            lengthA--;
            lengthB--;
        }
         while(lengthA >= 0){
            int num = (int)(a.charAt(lengthA)-'0')+carry;
            int k = num%2;
            carry = num/2;
            all = String.valueOf(k)+all;
            lengthA--;
        }
        if(carry == 1){
            all = "1"+all;
        }
        return all;
    }
}