LeetCode 67 -Add Binary

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a247027417/article/details/83474221

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"

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

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

示例 1:

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

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

【思路】

这道题,逻辑上十分简单,比较麻烦的就是位数的判定和需要从后往前计算。将a长度和b长度中较大的那一个作为循环的次数,当取出字符串中的值的时候,先判断一下是否超过了字符串长度,如果超出了直接用0计算,如果没有超出取出其值。计算的时候需要记录进位,当循环完之后,需要对进位进行判断,如果进位不为0,需要把其加在最前面。

【代码】

class Solution {
	
    public String addBinary(String a, String b) {
    	
        int max_length = a.length() > b.length() ? a.length() : b.length();
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        
        for (int j = 1;j <= max_length; j++ )
        {
        	int a_value = a.length() >= j ? ((int)(a.charAt(a.length()-j))-(int)('0')) : 0;
        	int b_value = b.length() >= j ? ((int)(b.charAt(b.length()-j))-(int)('0')) : 0;
        	int value = a_value + b_value + carry;
        	if (value >= 2)  { 
        		value = value - 2;
        		carry = 1;
        		}
        	else 
        		carry = 0;
        	sb.append(value);
        }
        if (carry == 1)
        	sb.append(1);
        sb.reverse();
    	return sb.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/a247027417/article/details/83474221