
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.
不使用内置 Int 类库,完成字符串的相加。
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
public String (String num1, String num2) {
if(num1 == null || num1.length() == 0) { return num2; } if(num2 == null || num2.length() == 0) { return num1; } char[] chAry = num1.toCharArray(); Stack<Character> aSk = new Stack<>(); for(Character a: chAry) { aSk.add(a); } char[] chBry = num2.toCharArray(); Stack<Character> bSk = new Stack<>(); for(Character b: chBry) { bSk.add(b); } int aLen = num1.length(); int bLen = num2.length(); List<Integer> result = new ArrayList<>(); int temp = 0; while (!aSk.isEmpty() || !bSk.isEmpty()) { char a = '0'; if(!aSk.isEmpty()) { a = aSk.pop(); } char b = '0'; if(!bSk.isEmpty()) { b = bSk.pop(); } int res = a + b - 96 + temp; if (res >= 10){ temp = 1; res = res - 10; } else { temp = 0; } result.add(res); } StringBuilder build = new StringBuilder(); int size = result.size(); if (temp == 1){ build.append(1); } for (int i= size - 1 ; i >= 0 ; i--){ build.append(result.get(i)); } return build.toString(); }
|
讨论区其他答案
1 2 3 4 5 6 7 8 9 10 11
|
public String (String num1, String num2) { StringBuilder sb = new StringBuilder(); int carry = 0; for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry == 1; i--, j--){ int x = i < 0 ? 0 : num1.charAt(i) - '0'; int y = j < 0 ? 0 : num2.charAt(j) - '0'; sb.append((x + y + carry) % 10); carry = (x + y + carry) / 10; } return sb.reverse().toString(); }
|
参考资料
近期评论