Leetcode 415. Add Strings

来源:互联网 发布:知乎经典回复 编辑:程序博客网 时间:2024/06/08 05:01

Leetcode 415. Add Strings


Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路:字符串模拟加法
class Solution {    public String addStrings(String num1, String num2) {        if(num1.length() < num2.length()) { // 让num1始终为较长的那个字符串            String temp = num1;            num1 = num2;            num2 = temp;        }        int len1 = num1.length();        int len2 = num2.length();        num1 = new StringBuilder(num1).reverse().toString(); //逆序        num2 = new StringBuilder(num2).reverse().toString();        StringBuilder sb = new StringBuilder();        int carry = 0; // 进位        for(int i = 0 ; i < len1; i++) {            int a = num1.charAt(i) - '0';            int b = (i < len2) ? num2.charAt(i) - '0' : 0;            int r = a + b + carry; // 别忘了加上进位            if(r >= 10) {                r %= 10;                 carry = 1;            }else {                carry = 0;            }            sb.append(r);        }         if(carry == 1) sb.append(carry); // 如果最后还有进位,别忘了加上        return sb.reverse().toString();    }}

这里写图片描述

原创粉丝点击