标题

题目描述:给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

提示:

  • num1 和num2 的长度都小于 5100
  • num1 和num2 都只包含数字 0-9
  • num1 和num2 都不包含任何前导零
  • 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-strings/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:遍历字符串

首先,声明一个字符串result为最后的返回值,声明所以为i初始值为0,addOne为进位值初始为0,firstNum和secondNum分别为num1和num2当前索引位的数字,然后开始遍历num1和num2中的元素,处理过程如下:

  • 如果i没有超过num1和num2的长度,则分别将num1和num2中当前索引位置的数字赋值给firstNum和secondNum,否则将firstNum和secondNum赋值为0;
  • 然后计算firstNum + secondNum + addOne结果为sum;
  • 如果sum大于9,则需要进位,addOne被重置为1,且将sum-10添加到result的字符串前面;
  • 如果sum小于9,则不需要进位,addOne被重置为0,且将sum添加到result的字符串前面;
  • i加1。

最后,判断addOne为1,则将addOne添加到result前面。

最后返回result即为字符串相加的结果。

  1. /**
  2. * @Author: ck
  3. * @Date: 2021/9/29 8:34 下午
  4. */
  5. public class LeetCode_415 {
  6. public static String addStrings(String num1, String num2) {
  7. String result = "";
  8. // addOne为进位
  9. int i = 0, addOne = 0, firstNum = 0, secondNum = 0;
  10. while (i < num1.length() || i < num2.length()) {
  11. if (i < num1.length()) {
  12. // num1中当前位的数字
  13. firstNum = num1.charAt(num1.length() - 1 - i) - '0';
  14. } else {
  15. firstNum = 0;
  16. }
  17. if (i < num2.length()) {
  18. // num2中当前位的数字
  19. secondNum = num2.charAt(num2.length() - 1 - i) - '0';
  20. } else {
  21. secondNum = 0;
  22. }
  23. int sum = firstNum + secondNum + addOne;
  24. if (sum > 9) {
  25. result = (sum - 10) + result;
  26. addOne = 1;
  27. } else {
  28. result = sum + result;
  29. addOne = 0;
  30. }
  31. i++;
  32. }
  33. if (addOne == 1) {
  34. result = 1 + result;
  35. }
  36. return result;
  37. }
  38. public static void main(String[] args) {
  39. // 期望输出: 533
  40. System.out.println(addStrings("456", "77"));
  41. }
  42. }

【每日寄语】 诚信是做人之母,务实乃成功之道。