Leetcode_Add Two Numbers

来源:互联网 发布:大数据培训学校 编辑:程序博客网 时间:2024/05/16 15:21

Add Two Numbers

 

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

已下是java实现:

1、已知下列ListNode的数据结构

 public static class ListNode {     int val;     ListNode next;     ListNode(int x) { val = x; } }
2、方法如下:

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {int add = 0;//存储进位int res = 0;//存储每一位相加的结果ListNode ln = new ListNode(0);ListNode key = ln;//key是当前节点while(l1!=null && l2!=null){//处理l1、l2都不为空的情况res = l1.val+l2.val+add;if(res>9){add=1;res=res-10;}else{add=0;}ListNode temp = new ListNode(res);key.next=temp;key=temp;l1=l1.next;l2=l2.next;}if(l1!=null){//处理只剩l1的情况while(l1!=null){res = l1.val+add;if(res>9){add=1;res=res-10;}else{add=0;}ListNode temp = new ListNode(res);key.next=temp;key=temp;l1=l1.next;}}else if(l2!=null){//处理只剩l2的情况while(l2!=null){res = l2.val+add;if(res>9){add=1;res=res-10;}else{add=0;}ListNode temp = new ListNode(res);key.next=temp;key=temp;l2=l2.next;}}if(add==1){//处理最后一位有进位的情况ListNode temp = new ListNode(1);key.next=temp;key=temp;}return ln.next;       }


3、写一个测试主方法

public static void main(String[] args) {ListNode l1 = new ListNode(2) ;l1.next=new ListNode(8);ListNode l2 = new ListNode(5) ;l2.next=new ListNode(9);l2.next.next=new ListNode(9);ListNode ln =addTwoNumbers(l1,l2);while(ln!=null){System.out.println(ln.val+"------");ln=ln.next;}}


4、相当于

Input: (2 -> 8) + (5 -> 9 -> 9)
Output: 7 -> 7 -> 0- > 1

0 0
原创粉丝点击