LeetCode 字符串相加(415题)

LeetCode 字符串相加

@author:Jingdai
@date:2020.09.25

题目描述(415题)

给定两个字符串形式的非负整数 num1num2 ,计算它们的和。

不能使用任何 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

思路

这个其实没什么好说的,就是简单记录一下代码。从低位开始各个位相加,有进位记录进位,直接看代码。

代码

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();
}

其实,上面代码还可以再次进行优化一点,直接用一个变量记录每次加的结果,直接看代码。

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();
}

猜你喜欢

转载自blog.csdn.net/qq_41512783/article/details/108802860