二进制求和 (Add Binary)

 

思路:

// @Title: 二进制求和 (Add Binary)
// @Author: qisiii
// @Date: 2024-01-02 13:26:04
// @Runtime: 1 ms
// @Memory: 41.3 MB
// @comment: 
// @flag: 
class Solution {
    public String addBinary(String a, String b) {
        int n=a.length()>b.length()?a.length()+1:b.length()+1;
        int[] c=new int[n];
        int jin=0;
        for (int i = 1; i < c.length+1; i++) {
            int av=a.length()-i>=0?a.charAt(a.length()-i)-48:0;
            int bv=b.length()-i>=0?b.charAt(b.length()-i)-48:0;
            int sum=av+bv+jin;
            c[n-i]=sum%2;
            jin=sum/2;
        }
        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0; i < c.length; i++) {
            if (i==0&&c[i]==0){
                continue;
            }
            stringBuffer.append(c[i]);
        }
        return stringBuffer.toString();
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18