大數相乘解決方案

會說話的湯姆發表於2020-11-05
public class Solution {
   if(num1.equals("0") || num2.equals("0")) {
      return "0";
   }
   int len1 = num1.length();
   int len2 = num2.length();
   
   int[] ansArr = new int[len1 + len2];
   
   for(int i = len1 - 1; i >= 0; i--){
      int x = num1.charAt(i) - '0';
      for(int j = len2 - 1; j >= 0; j--) {
         int  y = num2.charAt(j) - '0';
         ansArr[i+j+1] += x * y;
      } 
   }
   for(int i = len1 + len2 - 1; i > 0; i--) {
      ansArr[i-1] = ansArr[i] / 10;
      ansArr[i] %= 10;
   }
   
   //[0][][][]
   StringBuilder ans = new StringBuilder();
   int index = ansArr[0] == 0 ? 1 : 0;
   while(index < len1 + len2) {
       ans.append(ansArr[index]);
       index++;
   }
   return ans.toString();
}

字串相加

class Solution {
    public String addStrings(String num1, String num2) {
        if(num1.equals("0")){
            return num2;
        }
        if(num2.equals("0")){
            return num1;
        }
        int len1 = num1.length();
        int len2 = num2.length();

        int maxLen = Math.max(len1, len2);

        int[] sums = new int[maxLen];

        for(int i = 0; i < len1; i++) {
            sums[i] = num1.charAt(len1-i-1) - '0'; 
        }
         
        for(int j = 0; j < len2; j++){
            sums[j] += num2.charAt(len2-j-1) - '0';
        }

        for(int i = 0; i < sums.length-1; i++){
            if(sums[i] > 9) {
                sums[i+1] += sums[i] / 10;
                sums[i] %= 10;
            }
        }

        StringBuilder sb = new StringBuilder();
        for(int i = sums.length - 1; i >= 0; i--){
            sb.append(sums[i]);
        }
        String res = sb.toString();
        if(res.startsWith("0")){
            res = res.substring(1);
        }
        return res;  
    }
}

相關文章