每日AC--leetcode-- 2.Add Two Numbers

深入理解数据库原理
以实战为基础,以数据库原理为基础,结合实战,深入理解数据库原理。
wangxiaoming


每日AC--leetcode-- 2.Add Two Numbers


题目描述:

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


AC代码:

import common.ListNode;

/**
 * 类说明
 * 
 * <pre>
 * Modify Information:
 * Author        Date          Description
 * ============ =========== ============================
 * DELL          2017年8月3日    Create this file
 * </pre>
 * 
 */

public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode  rear = new ListNode(0);
        rear.next = null;
        ListNode p = l1, q = l2, cur = rear;
        int increase = 0;
        while(p != null  || q != null){
            int x =  (p==null)?0:p.val;
            int y = (q == null)?0:q.val;
            int z = x+y+increase;
            int yu = z%10;
            increase = z/10;
            //尾插法建立链表
            ListNode newNode = new ListNode(yu);
            cur.next = newNode;
            cur  = newNode;
            
            // 两个链表都往下走
            if(p != null){
                p = p.next; 
            }
            
            if(q != null){
                q = q.next;
            }
        }
        // 最后有个 还有进位的话 要考虑进来
        if(increase >0){
            cur.next = new ListNode(increase);
        }
        return rear.next;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = null;
        
        
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        ListNode node7 = new ListNode(7);
        ListNode node8 = new ListNode(8);
        
        node5.next = node6;
        node6.next = node7;
        node7.next = node8;
        node8.next = null;
        
        ListNode  ansNode = new AddTwoNumbers().addTwoNumbers(node1, node5);
        
        while(ansNode != null){
            System.out.print(ansNode.val +"->");
            ansNode = ansNode.next;
        }
    }

}



wangxiaoming CSDN认证博客专家 架构 Spring Boot Redis
博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com
©️2020 CSDN 皮肤主题: Age of Ai 设计师: meimeiellie 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值