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;
            
        }
    }
  • 相关阅读:
    16进制数至字符串转换
    综合评价模型C++实现
    综合评价模型
    Eigen使用矩阵作为函数参数
    Eigen子矩阵操作
    Eigen矩阵基本运算
    c++矩阵运算库Eigen简介
    三次样条插值算法C++实现
    一个 图片 滚动 飞入的css特效
    在TTF字体中提取想要的文字
  • 原文地址:https://www.cnblogs.com/hygeia/p/4765747.html
Copyright © 2011-2022 走看看