1. 程式人生 > 其它 >牛客網刷題-大數加法

牛客網刷題-大數加法

技術標籤:演算法Java演算法面試

問題描述

以字串的形式讀入兩個數字,編寫一個函式計算它們的和,以字串形式返回。
(字串長度不大於100000,保證字串僅由’0’~'9’這10種字元組成)

輸入描述:
輸入兩個字串格式數字

輸出描述:
輸出數字相加的和

示例

示例1

輸入
“1”,“99”

輸出
“100”

解決思路

分析

  1. 從末位向前依次處理,處理進位的情況,需要處理相加和超出最長字串位數的情況

方法

  1. 通過迴圈從末位向前依次處理,處理進位的情況,需要處理相加和超出最長字串位數的情況

程式碼實現

// 思路1
public class Solution {  
    public String solve (
String s, String t) { // write code here if (s == null && s.length() == 0) { return t; } if (t == null && t.length() == 0) { return s; } if (s.length() < t.length()) { String temp = s; s = t;
t = temp; } int temp = 0; int i = s.length() - 1, j = t.length() - 1; char[] result = new char[s.length()]; while (i >= 0 && j >= 0) { int a = s.charAt(i) - '0'; int b = t.charAt(j) - '0'; int c = a +
b + temp; if (c >= 10) { temp = c / 10; c %= 10; } else { temp = 0; } result[i] = (char) ('0' + c); i--; j--; } while (i >= 0) { int a = s.charAt(i) - '0'; int c = a + temp; if (c >= 10) { temp = c / 10; c %= 10; } else { temp = 0; } result[i] = (char) ('0' + c); i--; } String val = new String(result); if (temp > 0) { return String.valueOf(temp) + val; } return val; } }

小夥伴如果想測試的話,可以直接到牛客網這個連結做測試

大數加法-牛客網