LeetCode: 二进制求和

题目链接:https://leetcode-cn.com/problems/add-binary/description/

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

示例 1:

输入: a = "11", b = "1"
输出: "100"
示例 2:

输入: a = "1010", b = "1011"
输出: "10101"

思路 和两个大数字求和一样 利用数学加法的思想

class Solution { 
    public int charToInt(char c){
     
        return (c-'0');
    } 
    public String addBinary(String a, String b) {
        if(a==null&&b==null){
            return null;
        }
        String result="";
        int jw=0;
        int len1=a.length();
        int len2=b.length();   
        int min=len1<len2?len1:len2;
        while(true){
           if(min>0)  {     
            int temp=charToInt(a.charAt(--len1))+charToInt(b.charAt(--len2))+jw;
           if(temp==2){jw=1;result+="0";}  
            if(temp==3){jw=1;result+="1";}
            if(temp==1){jw=0;result+="1";}
            if(temp==0){jw=0;result+="0";} 
           min--;
            }else{
                while(len1>0){
                    int temp=charToInt(a.charAt(--len1))+jw;
                     if(temp==2){jw=1;result+="0";}  
                     if(temp==3){jw=1;result+="1";}
                     if(temp==1){jw=0;result+="1";}
                     if(temp==0){jw=0;result+="0";}
                }
                 while(len2>0){
                    int temp=charToInt(b.charAt(--len2))+jw;
                     if(temp==2){jw=1;result+="0";}  
                     if(temp==3){jw=1;result+="1";}
                     if(temp==1){jw=0;result+="1";}
                     if(temp==0){jw=0;result+="0";}
                }
               break;
            }         
        }
        if(jw==1)
           result+="1";
        
        return new  StringBuilder(result).reverse().toString();
    }
}

猜你喜欢

转载自blog.csdn.net/smile__dream/article/details/82019116