zoukankan      html  css  js  c++  java
  • LeetCode之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.

    Example

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.

    题目不难,直接上代码。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode result = null, tmp = null;//tmp作为指针使用,进行移动
            int n = 0;
            int v1 = 0, v2 = 0;
            while(l1 != null || l2 != null)
            {
                if(l1 != null)
                {
                    v1 = l1.val;
                }
                if(l2 != null)
                {
                    v2 = l2.val;
                }
                
                //第一次进行计算
                if(result == null)
                {
                    result = new ListNode((v1 + v2) % 10);
                    tmp = result;
                    n = (v1 + v2)/10;
                }
                else
                {
                    ListNode next = new ListNode((v1 + v2 + n) % 10);//避免超过10,我们只需要个位数字
                    tmp.next = next;
                    tmp = next;
                    n = (v1 + v2 + n) / 10;
                }
               
                v1 = 0;
                v2 = 0;
                if (l1 != null)
                {
                    l1 = l1.next; 
                }
                if (l2 != null)
                {
                    l2 = l2.next;
                }
            }
            if(n > 0)
            {
                tmp.next = new ListNode(n);
            }
            return result;
        }
    }
  • 相关阅读:
    校园网络安全CTF 第一题 和 你真了解我吗?
    href="#" 链接到当前页面
    Redis的Set无序集合命令
    Redis的List链表类型命令
    Redis的String、Hash类型命令
    redis2.8.xx安装配置
    ZendFramework安装配置
    复选框的全选、反选
    列表中被点击的行加亮背景色
    SQL中的替换函数replace()使用
  • 原文地址:https://www.cnblogs.com/woniu4/p/8184853.html
Copyright © 2011-2022 走看看