java [415。添加字符串] #Leetcode #Medium #BigInt(String)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java [415。添加字符串] #Leetcode #Medium #BigInt(String)相关的知识,希望对你有一定的参考价值。

/* Given two non-negative integers num1 and num2 represented as string, 
    return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
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) {
    
    // corner case
    if(num1 == null || num1.length() == 0)
      return num2;
    
    if(num2 == null || num2.length() == 0)
      return num1;
    
    // use StringBuilder to store the reversed result.
    StringBuilder sb = new StringBuilder();
    int index1 = num1.length()-1;
    int index2 = num2.length()-1;
    int z = 0;
    
    // iterate two String from right to left
    while(index1 >= 0 || index2 >= 0){
      //empty position will be taken as 0
      int x = index1 >= 0 ? num1.charAt(index1) - '0': 0;
      int y = index2 >= 0 ? num2.charAt(index2) - '0': 0;
      sb.append((x + y + z) % 10);
      z = (x + y + z) / 10;
      index1--;
      index2--;
    }
    
    // add an extra digit
    if(z == 1)
      sb.append("1");
    
    // return reversed StringBuilder
    return sb.reverse().toString();
  
  }

}

以上是关于java [415。添加字符串] #Leetcode #Medium #BigInt(String)的主要内容,如果未能解决你的问题,请参考以下文章

java 415.添加Strings.java

java 415.添加Strings.java

java 415.添加Strings.java

java 415.添加Strings.java

java 415.添加Strings.java

精选力扣500题 第26题 LeetCode 415. 字符串相加c++ / java 详细题解