【算法】两个数字相加(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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

LeetCode 第2题,通常面试的时候有时候会被这样文档,请设计一个不限制长度的计算器。即为这个问题。

我们顺便学习下英文,程序员必须掌握英文:

给到两个非空的链表来表示两个非负的整数。数字以逆序的方式存储,并且每个节点仅包含一位数字。将两个数字相加返回一个同样结构的链表。

你可以假设数据的数字高位不会是以0开头。

解这个题目有两种思路一种是循环的方式:(这种方式效率相对低耗时较长)

/**
     * 数据结构
     */
    static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    /**
     * solution
     * Runtime: 4 ms, faster than 50.33% of Java online submissions for Add Two Numbers.
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode result = new ListNode(0);

        ListNode first = l1;
        ListNode second = l2;
        ListNode current = result;
        ListNode previous = result;
        // 记录低位到高位的溢出值
        int overflowValue = 0;

        while (first != null || second !=null) {
            if (current == null) {
                current = new ListNode();
                previous.next = current;
                previous = current;
            }
            // 计算
            int firstValue = 0;
            if (first != null) {
                firstValue = first.val;
            }
            int secondValue = 0;
            if (second != null) {
                secondValue = second.val;
            }
            // 0-19
            int tempSum = firstValue + secondValue + overflowValue;
            if (tempSum > 9) {
                overflowValue = tempSum / 10;
                tempSum = tempSum % 10;
                current.val = tempSum;
            } else {
                current.val = tempSum;
                overflowValue = 0;
            }

            if (first != null) {
                first = first.next;
            }
            if (second != null) {
                second = second.next;
            }
            current = current.next;
        }

        if (overflowValue > 0) {
            ListNode last = new ListNode(overflowValue);
            current = last;
            previous.next = current;
        }

        return result;
    }

    @Test
    public void test () {
        //prepare
        ListNode first = new ListNode(9, new ListNode(9,new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
        ListNode second = new ListNode(9, new ListNode(9,new ListNode(9, new ListNode(9))));
        //execute
        ListNode result = addTwoNumbers(first, second);
        //verify
        while (result != null) {
            System.out.print(result.val + "-->");
            result =  result.next;
        }
        System.out.println("");
    }

另一种是递归的思想,可以看下我的另一片文章讲解递归的执行。这是一个简单的递归实现:

 /**
     * 数据结构
     */
    static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
/**
     * solution
     * Runtime: 2 ms, faster than 99.33% of Java online submissions for Add Two Numbers.
     * Memory Usage: 42.3 MB, less than 93.16% of Java online submissions for Add Two Numbers.
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode addTwoNumbersWithRecursion(ListNode l1, ListNode l2) {

        ListNode result = new ListNode(0);

        ListNode first = l1;
        ListNode second = l2;
        ListNode current = result;
        ListNode previous = result;
        // 记录低位到高位的溢出值
        int overflowValue = 0;

        add(first, second, current, previous, overflowValue);

        return result;
    }

    static void add(ListNode first, ListNode second, ListNode current, ListNode previous, int overflowValue) {
        if (first == null && second == null) {
            if (overflowValue > 0) {
                ListNode last = new ListNode(overflowValue);
                current = last;
                previous.next = current;
            }
            return;
        }
        if (current == null) {
            current = new ListNode();
            previous.next = current;
            previous = current;
        }
        // 计算
        int firstValue = 0;
        if (first != null) {
            firstValue = first.val;
        }
        int secondValue = 0;
        if (second != null) {
            secondValue = second.val;
        }
        // 0-19
        int tempSum = firstValue + secondValue + overflowValue;
        if (tempSum > 9) {
            overflowValue = tempSum / 10;
            tempSum = tempSum % 10;
            current.val = tempSum;
        } else {
            current.val = tempSum;
            overflowValue = 0;
        }

        if (first != null) {
            first = first.next;
        }
        if (second != null) {
            second = second.next;
        }
        current = current.next;
        add(first, second, current, previous, overflowValue);
    }

    @Test
    public void testRecursion () {
        //prepare
        ListNode first = new ListNode(9, new ListNode(9,new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
        ListNode second = new ListNode(9, new ListNode(9,new ListNode(9, new ListNode(9))));
        //execute
        ListNode result = addTwoNumbersWithRecursion(first, second);
        //verify
        while (result != null) {
            System.out.print(result.val + "-->");
            result =  result.next;
        }
        System.out.println("");
    }

### HTML 网页代码实现过年烟花效果 为了创建具有春节氛围的烟花效果,可以采用HTML5 `Canvas` 和 JavaScript 结合的方式。下面是一个简单版本的烟花爆炸动画示例: #### 完整HTML文件结构如下所示: ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>新年快乐 - 烟花秀</title> <style> body { margin: 0; overflow:hidden;background-color:#000;} canvas { display:block } </style> </head> <body> <canvas id="fireworks"></canvas> <script> class Particle { constructor(x, y) { this.x = x; this.y = y; this.color = 'hsl(' + Math.random() * 360 + ', 100%, 70%)'; this.size = Math.random() * 4 + 1; this.speedX = (Math.random() - .5) * 10; this.speedY = (Math.random() - .5) * 10; this.alpha = 1; } update(ctx) { ctx.globalAlpha = this.alpha -= 0.01; ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x += this.speedX, this.y += this.speedY, this.size, 0, Math.PI * 2); ctx.fill(); if (this.alpha <= 0) particles.splice(particles.indexOf(this), 1); } } let canvas = document.getElementById('fireworks'); let context = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; window.addEventListener('resize', function () { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }); function createFirework(event) { let mouseX = event.clientX || event.touches[0].clientX; let mouseY = event.clientY || event.touches[0].clientY; for (var i = 0; i < 100; i++) { particles.push(new Particle(mouseX, mouseY)); } } document.body.addEventListener('click', createFirework); let particles = []; function animate() { requestAnimationFrame(animate); context.clearRect(0, 0, innerWidth, innerHeight); for (let particle of particles) { particle.update(context); } } animate(); </script> </body> </html> ``` 此段脚本定义了一个名为Particle的对象来表示单个火花粒子,并设置了其属性如位置、颜色、大小以及速度等[^1]。 页面加载完成后会监听窗口尺寸变化事件以便调整画布大小适应不同设备屏幕;同时绑定了鼠标点击事件,在用户点击处生成一组随机分布的小颗粒模拟烟花的过程[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值