File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://leetcode.com/problems/add-strings/
2+ //
3+ // algorithms
4+ // Easy (44.7%)
5+ // Total Accepted: 114,595
6+ // Total Submissions: 256,348
7+
8+
9+ class Solution {
10+ public String addStrings (String num1 , String num2 ) {
11+ int len1 = num1 .length (), len2 = num2 .length ();
12+ if (len1 == 0 ) {
13+ return num2 ;
14+ }
15+ if (len2 == 0 ) {
16+ return num1 ;
17+ }
18+
19+ LinkedList <Integer > l = new LinkedList <>();
20+
21+ int idx1 = 0 , idx2 = 0 , carry = 0 ;
22+ while (idx1 < len1 || idx2 < len2 ) {
23+ int tmp = carry ;
24+ if (idx1 < len1 ) {
25+ tmp += (num1 .charAt (len1 - 1 - idx1 ) - '0' );
26+ idx1 ++;
27+ }
28+ if (idx2 < len2 ) {
29+ tmp += (num2 .charAt (len2 - 1 - idx2 ) - '0' );
30+ idx2 ++;
31+ }
32+
33+ if (tmp >= 10 ) {
34+ carry = 1 ;
35+ tmp -= 10 ;
36+ } else {
37+ carry = 0 ;
38+ }
39+
40+ l .addFirst (tmp );
41+ }
42+
43+ if (carry == 1 ) {
44+ l .addFirst (1 );
45+ }
46+
47+ StringBuilder sb = new StringBuilder ();
48+ for (int n : l ) {
49+ sb .append (n );
50+ }
51+
52+ return sb .toString ();
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments