zoukankan      html  css  js  c++  java
  • 【leetcode】2. Add Two Numbers

    小学生加法

    这题需要注意空指针、进位

    /**
     * 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 root = new ListNode(0);
            ListNode sum = root;
            int add = 0;
            while (l1 != null || l2 != null) {
                sum.val = value(l1) + value(l2) + add;
                if (sum.val >= 10) {
                    sum.val -= 10;
                    add = 1;
                } else {
                    add = 0;
                }
                if (l1 != null) {
                    l1 = l1.next;
                }
                if (l2 != null) {
                    l2 = l2.next;
                }
                if (l1 != null || l2 != null) {
                    sum.next = new ListNode(0);
                    sum = sum.next;
                } else if (add == 1) {
                    sum.next = new ListNode(1);
                }
            }
            return root;
        }
        
        private int value(ListNode n) {
            return n == null ? 0 : n.val;
        }
    }
  • 相关阅读:
    zookeeper学习笔记
    wsl笔记
    SSDB数据库笔记
    spring笔记
    redis笔记
    openresty配置
    openresty安装笔记
    mybatis笔记
    nginx配置
    STM32F373(青风)+CUBEMX快速上手
  • 原文地址:https://www.cnblogs.com/lanhj/p/5373221.html
Copyright © 2011-2022 走看看