当前位置:网站首页>LeetCode-2. Add Two Numbers

LeetCode-2. Add Two Numbers

2022-08-10 16:26:00 51CTO


 ​https://leetcode.com/problems/add-two-numbers/description/​

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

      
      
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
  • 1.
  • 2.
  • 3.

题解:

      
      
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int num1 = 0, num2 = 0, weight1 = 0, weight2 = 0;
ListNode * addTwoNumbers( ListNode * l1, ListNode * l2) {
ListNode * p = new ListNode( 0);
ListNode * head = p;
int flag_1 = 0;
int flag_2 = 0;
int carry = 0;
bool first = true;
while( true){
int sum_1, sum_2;
if( l1 != NULL){
sum_1 = l1 -> val;
l1 = l1 -> next;
}
else{
sum_1 = 0;
flag_1 = 1;
}
if( l2 != NULL){
sum_2 = l2 -> val;
l2 = l2 -> next;
}
else{
sum_2 = 0;
flag_2 = 1;
}
int sum = sum_1 + sum_2 + carry;
if( flag_1 == 1 && flag_2 == 1 && carry == 0){
break;
}
else if( flag_1 == 1 && flag_2 == 1 && carry == 1){
p -> next = new ListNode( sum);
p = p -> next;
break;
}
if( sum >= 10){
sum -= 10;
carry = 1;
}
else{
carry = 0;
}
if( first == true){
p -> val = sum;
first = false;
}
else{
p -> next = new ListNode( sum);
p = p -> next;
}
}
return head;
}
};
  • 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.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.

 

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_14150327/5564233