File tree 2 files changed +81
-0
lines changed
2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ struct ListNode {
2
+ int val;
3
+ ListNode *next;
4
+ ListNode () : val(0 ), next(nullptr ) {}
5
+ ListNode (int x) : val(x), next(nullptr ) {}
6
+ ListNode (int x, ListNode *next) : val(x), next(next) {}
7
+ };
8
+
9
+ class Solution {
10
+ public:
11
+ ListNode* addTwoNumbers (ListNode* l1, ListNode* l2) {
12
+ ListNode * head = new ListNode ();
13
+ ListNode * tmp = head;
14
+ int carry = 0 ;
15
+ while (l1 && l2)
16
+ {
17
+ tmp->next = new ListNode ((l1->val + l2->val +carry) % 10 );
18
+ carry = (l1->val + l2->val +carry) / 10 ;
19
+ tmp = tmp->next ;
20
+ l1 = l1->next ;
21
+ l2 = l2->next ;
22
+ }
23
+
24
+ while (l1)
25
+ {
26
+ tmp->next = new ListNode ((l1->val + carry) % 10 );
27
+ carry = (l1->val + carry) / 10 ;
28
+ tmp = tmp->next ;
29
+ l1 = l1->next ;
30
+ }
31
+
32
+ while (l2)
33
+ {
34
+ tmp->next = new ListNode ((l2->val + carry) % 10 );
35
+ carry = (l2->val + carry) / 10 ;
36
+ tmp = tmp->next ;
37
+ l2 = l2->next ;
38
+ }
39
+
40
+ if (carry != 0 ){
41
+ tmp->next = new ListNode (carry);
42
+ }
43
+
44
+ tmp = head;
45
+ head = head->next ;
46
+ delete tmp;
47
+ return head;
48
+ }
49
+ };
Original file line number Diff line number Diff line change
1
+ #include < string>
2
+ #include < iostream>
3
+ #include < vector>
4
+ using namespace std ;
5
+ class Solution {
6
+ public:
7
+ string multiply (string num1, string num2) {
8
+ if (num1 == " 0" || num2 == " 0" )
9
+ return " 0" ;
10
+ string res;
11
+ int m = num1.size (), n = num2.size ();
12
+ vector<int > arr (m + n);
13
+ for (int index1 = m -1 ; index1 >= 0 ; --index1)
14
+ {
15
+ for (int index2 = n - 1 ; index2 >= 0 ; --index2){
16
+ int tmp1 = num1[index1] - ' 0' , tmp2 = num2[index2] - ' 0' ;
17
+ arr[index1 + index2 + 1 ] += tmp1 * tmp2;
18
+ }
19
+ }
20
+
21
+ for (int i = m + n - 1 ; i > 0 ; --i){
22
+ int tmp = arr[i];
23
+ arr[i] = tmp % 10 ;
24
+ arr[i-1 ] = arr[i-1 ] + tmp / 10 ;
25
+ }
26
+ int start = arr[0 ] == 0 ? 1 : 0 ;
27
+ for (int i = start; i < m + n; ++i){
28
+ res.push_back (arr[i] + ' 0' );
29
+ }
30
+ return res;
31
+ }
32
+ };
You can’t perform that action at this time.
0 commit comments