首页 > 代码库 > LeetCode 002 Add Two Numbers - Java
LeetCode 002 Add Two Numbers - Java
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
定位:中等题
题意简单,两个倒置的非负整数,用链表存储,链表类的定义也给出:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
现在要将这两数相加后得到的数也倒置用链表存储,因为已经倒置的缘故,低位在前,直接处理,不断向高位推进。
需要注意就是进位问题,当所有都处理完,最后还有进位存在,链表的最后还要加一个节点,值为1,即最高位为1.
Java实现:
1 public class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 ListNode listNode=new ListNode(0); 4 ListNode ptr1,ptr2,ptr; 5 int addp=0; 6 int now; 7 ptr1=l1; 8 ptr2=l2; 9 ptr=listNode; 10 while (ptr1!=null&&ptr2!=null){ 11 now=ptr1.val+ptr2.val+addp; 12 addp=0; 13 if(now>9){ 14 addp++; 15 now-=10; 16 } 17 ptr.next=new ListNode(now); 18 ptr=ptr.next; 19 ptr1=ptr1.next; 20 ptr2=ptr2.next; 21 } 22 while (ptr1!=null){ 23 now=ptr1.val+addp; 24 addp=0; 25 if(now>9){ 26 addp++; 27 now-=10; 28 } 29 ptr.next=new ListNode(now); 30 ptr=ptr.next; 31 ptr1=ptr1.next; 32 } 33 while (ptr2!=null){ 34 now=ptr2.val+addp; 35 addp=0; 36 if(now>9){ 37 addp++; 38 now-=10; 39 } 40 ptr.next=new ListNode(now); 41 ptr=ptr.next; 42 ptr2=ptr2.next; 43 } 44 if(addp==1){ 45 ptr.next=new ListNode(addp); 46 } 47 return listNode.next; 48 } 49 }
LeetCode 002 Add Two Numbers - Java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。