Java-LeetCode-Add Two Numbers

        You are given two linked lists representingtwo non-negative numbers. The digits are stored in reverse order and each oftheir nodes contain a single digit. Add the two numbers and return it as alinked list.

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

        解决该题的关键是要明确题意,实现加数和超过10之后,对应链表的位置保存的是个位数(temp % 10),而十位上的数字要以加数的形式和参加运算。尤其是在链表的最后,防止超10的情况发生,要判断这种情况。

/**
	 * Definition for singly-linked list.
	 * public class ListNode {
	 *     int val;
	 *     ListNode next;
	 *     ListNode(int x) { val = x; }
	 * }
	 */
	public class Solution {
	    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	        if(l1 == null || l2 == null){
	            return null;
	        }
	        
	        ListNode l3 = new ListNode(0);//创建l3要赋值
	        ListNode p1 = l1, p2 = l2, p3 = l3;
	        int temp = 0;
	        
	        while(p1 != null || p2 != null){
	            
	            if(p1 != null){
	                temp = temp + p1.val;
	                p1 = p1.next;
	            }
	            
	            if(p2 != null){
	                temp = temp + p2.val;
	                p2 = p2.next;
	            }
	            
	            p3.next = new ListNode(temp % 10);
	            p3 = p3.next;
	            temp = temp / 10;//记得将两数的和的十位加到l3的next的val中
	            
	        }
	        
	        if(temp == 1){//防止两个链表的最后结点相加的和大于10的情况
	            p3.next = new ListNode(1);
	        }
	        return l3.next;
	    }
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值