LeetCode string addition (415 questions)

LeetCode string addition

@author:Jingdai
@date:2020.09.25

Topic description (415 questions)

Given two non-negative integer to a string num1and num2calculates their sum.

You cannot use any BigInteger library, nor can you directly convert the input string into an integer form.

Ideas

There is nothing to say about this, just simply record the code. Starting from the low bit, each bit is added, there is a carry to record the carry, look at the code directly.

Code

public String add(String num1, String num2) {
     
     

    int i = num1.length() - 1;
    int j = num2.length() - 1;
    int overflow = 0;

    StringBuilder ans = new StringBuilder();
    while (i >= 0 || j >= 0 || overflow != 0) {
     
     
        int first = i >= 0 ? num1.charAt(i) - '0' : 0; 
        int second = j >= 0 ? num2.charAt(j) - '0' : 0;
        int temp = first + second + overflow;
        ans.append(temp % 10);
        overflow = temp / 10;
        i --;
        j --;
    }

    return ans.reverse().toString();
}

In fact, the above code can be optimized a bit again, directly use a variable to record the result of each addition, and look at the code directly.

public String add(String num1, String num2) {
     
     
    
	int i = num1.length() - 1;
	int j = num2.length() - 1;
	int item = 0; 
	StringBuilder ans = new StringBuilder();
	while (i >= 0 || j >= 0 || item != 0) {
     
     
		if (i >= 0) {
     
     
			item += num1.charAt(i--) - '0';
		}
		if (j >= 0) {
     
     
			item += num2.charAt(j--) - '0';
		}
		ans.append(item % 10);
		item /= 10;
	}
    
	return ans.reverse().toString();
}

Guess you like

Origin blog.csdn.net/qq_41512783/article/details/108802860