-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path415.add-strings.java
More file actions
51 lines (46 loc) · 1.27 KB
/
Copy path415.add-strings.java
File metadata and controls
51 lines (46 loc) · 1.27 KB
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
/*
* @lc app=leetcode id=415 lang=java
*
* [415] Add Strings
*
* https://leetcode.com/problems/add-strings/description/
*
* algorithms
* Easy (44.29%)
* Total Accepted: 145.5K
* Total Submissions: 316.2K
* Testcase Example: '"0"\n"0"'
*
* 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) {
int i = 0;
int c = 0;
StringBuilder sb = new StringBuilder();
while (num1.length() > i || num2.length() > i || c != 0) {
int v = c;
if (i < num1.length()) {
v += Character.getNumericValue(num1.charAt(num1.length() - 1 - i));
}
if (i < num2.length()) {
v += Character.getNumericValue(num2.charAt(num2.length() - 1 - i));
}
c = v / 10;
sb.insert(0, v % 10);
i++;
}
return sb.toString();
}
}