欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Task10.两数相加

程序员文章站 2024-03-15 23:22:12
...

LeetCode 两数之和

题目

Task10.两数相加

代码

/** 
 * Definition for singly-linked list. 
 * public class ListNode { 
 *     public int val; 
 *     public ListNode next; 
 *     public ListNode(int x) { val = x; } 
 * }
 */
 public class Solution 
 {    
     public ListNode AddTwoNumbers(ListNode l1, ListNode l2) 
     {        
         int val = 0;        
         ListNode temp = new ListNode();        
         ListNode lastNode = temp;        
         while (l1 != null || l2 != null || val != 0)        
         {            
             val = val + (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val);            
             lastNode.next = new ListNode();
             lastNode.next.val = val % 10;            
             lastNode = lastNode.next; 
             val = val / 10;            
             l1 = l1 == null ? null : l1.next;            
             l2 = l2 == null ? null : l2.next;        
         }        
         return temp.next;    
     }
}

Task10.两数相加

相关标签: LeetCode 实战