Skip to content

Leetcode: Add Binary (Java) How can it perform addition between one char and one int?

class Solution {
    public String addBinary(String a, String b) {
        int len1 = a.length() - 1;
        int len2 = b.length() - 1;
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        while (len1 >= 0 || len2 >= 0){
            int sum = carry;
            if (len1 >= 0) sum += a.charAt(len1) - '0';
            if (len2 >= 0) sum += b.charAt(len2) - '0';
            carry = sum/2;
        if(carry != 0) sb.append(carry);
        return sb.reverse().toString(); 

Apparently, this code works for the solution, I’m just having a hard time understanding the question. For this line:

sum += a.charAt(len1) - '0';

sum is an integer, a.charAt(len1) returns a char, how can it perform addition between an integer and a char? also, what does it mean to – ‘0’?



chars are essentially smaller ints with fancy printing associated to them. A char actually holds the unicode code for a specific character, and can be treated as an integer for addition and subtraction. A neat thing about this is that the characters that represents digits are sequential (‘0’ is followed by ‘1’, which is followed by ‘2’, etc). So if you subtract ‘0’ (i.e., “the unicode code for the character 0) from a char, you’ll get the actual digit it represents.

5 People found this is helpful