Leetcode 67

英文原题

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"

中文题意

输入为两个二进制的字符串,对两个字符串的内容进行加操作,结果用字符串表示

分析

1.字符和数字之间的转换问题

字符之间的加、减运算,是其对应的ASCII码之间的运算,‘0’对应的ASCII码十进制为48。

数字和字符之间的转换:int ele = 48;char res = (char)ele;

2.进位问题

3.字符串和数字之间的转换


java代码

class Solution {
    public String addBinary(String a, String b) {
        int first = a.length();
        int second = b.length();
        int[] farr = new int[first];
        int[] sarr = new int[second];
        int[] res = new int[first > second? first:second];
        StringBuffer resstr=new StringBuffer();
        
        int flag = 0;
        int temp;
        int rescount = res.length -1;
        
        for(int i = 0;i<first;i++){
            if(a.charAt(i) == '0'){
                farr[i] = 0;
            }else{
                farr[i] = 1;
            }
        }
        
        for(int j = 0;j<second;j++){
            if(b.charAt(j) == '0'){
                sarr[j] = 0;
            }else{
                sarr[j] = 1;
            }
        }
        
        first--;
        second--;
        
        while(first >=0 && second>=0){
            temp = (farr[first]+sarr[second]+flag)/2;
            res[rescount--] = (farr[first]+sarr[second]+flag)%2;
            flag = temp;
            first--;
            second--;
        }
        
        while(first >= 0){
            temp = (farr[first] + flag)/2;
            res[rescount--] = (farr[first]+flag)%2;
            flag = temp;
            first--;
        }
        
        while(second >=0 ){
            temp = (sarr[second] + flag)/2;
            res[rescount--] = (sarr[second]+flag)%2;
            flag = temp;
            second--;
        }
        
        if(flag == 1){
            resstr.append(flag);
        }
        
        for(int ele : res){
            resstr.append(ele);
        }
        
        return resstr.toString();
        
    }
}

猜你喜欢

转载自blog.csdn.net/xingkong_04/article/details/80658298