leetcode------Add Two Numbers

标题: Add Two Numbers
通过率: 22.6%
难度: 中等

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

本题是比较弱的。要注意的就是两个链表的长度不一样,在这里我还考虑了余数大于十的问题。

代码如下:

 1 /**

 2  * Definition for singly-linked list.

 3  * public class ListNode {

 4  *     int val;

 5  *     ListNode next;

 6  *     ListNode(int x) {

 7  *         val = x;

 8  *         next = null;

 9  *     }

10  * }

11  */

12 public class Solution {

13     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

14         int list1num=-1,list2num=-1;

15         ListNode res=new ListNode(1);

16         ListNode result=res;

17         int carry=0,sum=0;

18         boolean flag=true;

19         while(flag){

20             if(l1!=null&l2!=null){

21                 list1num=l1.val+carry;

22                 list2num=l2.val;

23                 carry=0;

24                 carry=(list1num+list2num)/10;

25                 sum=(list1num+list2num)%10;

26                 ListNode temp=new ListNode(sum);

27                 res.next=temp;

28                 res=temp;

29                 l1=l1.next;

30                 l2=l2.next;

31             }

32             else if(l1!=null&&l2==null){

33                 list1num=l1.val+carry;

34                 carry=0;

35                 carry=list1num/10;

36                 sum=list1num%10;

37                  ListNode temp=new ListNode(sum);

38                 res.next=temp;

39                 res=temp;

40                 l1=l1.next;

41             }

42             else if(l1==null&&l2!=null){

43                  list2num=l2.val+carry;

44                 carry=0;

45                 carry=list2num/10;

46                 sum=list2num%10;

47                  ListNode temp=new ListNode(sum);

48                 res.next=temp;

49                 res=temp;

50                 l2=l2.next;

51             }

52             else {

53                 flag=false;

54                 

55             }

56 

57         }

58         while((carry/10!=0)||(carry%10!=0)){

59              ListNode temp=new ListNode(carry%10);

60              carry=carry/10;

61              res.next=temp;

62              res=temp;

63         }

64         return result.next;

65         

66     }

67 }

 

你可能感兴趣的:(LeetCode)