zoukankan      html  css  js  c++  java
  • Add two numbers

    题目:

    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

    代码:

    /**
     * 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) return l2;
            if(l2==null) return l1;
            if(l1==null&&l2==null) return null;
            ListNode node = new ListNode(0) ;
            ListNode head = node;
            int carry = 0;
            while(l1!=null&&l2!=null)
            {
                int res = l1.val+l2.val+carry;
                node.next = new ListNode(res % 10);
                carry = res/10;
                l1 = l1.next;
                l2 = l2.next;
                node = node.next;
            }
            while(l1!=null){
                int res = l1.val+carry;
                node.next = new ListNode(res % 10);
                carry = res/10;
                l1 = l1.next;
                node = node.next;
            }
            while(l2!=null){
                int res = l2.val+carry;
                node.next = new ListNode(res % 10);
                carry = res/10;
                l2 = l2.next;
                node = node.next;        
            }
            if(carry!=0){
                node.next = new ListNode(carry);
            }
            
            return head.next;
            
        }
    }
  • 相关阅读:
    win10自动休眠解决方法
    创世纪游戏、黄金分割比
    placeholder和assign速度对比
    内耗
    windows下编写dll
    北航院系和数字的对应关系
    maven Could not resolve dependencies
    java9模块不可见问题
    maven-dependencies插件的模拟实现
    Freemarker简单封装
  • 原文地址:https://www.cnblogs.com/hygeia/p/4765747.html
Copyright © 2011-2022 走看看