LeetCode 002 Add Two Numbers - Java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode刷题系列 - 002题Add Two Numbers