zoukankan      html  css  js  c++  java
  • LeetCode Linked List Medium 2. Add Two Numbers

     Description


    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.

     题目描述:两个非空链表,代表两个非负整数。链表从尾部到头部每一个元素代表非负整数的每一位的值。技术这两个数的值,并把结果放到一个链表中。

    我的思路:链表长度不限,所以不能转成int 或者long 进行计算。同时 每一位进行计算的时候,会有进位产生。下面是我的解法

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
            ListNode res = new ListNode(0);
            ListNode temp = res;
            bool flag = false;
            int sum = 0;
            while(l1 != null && l2 != null){
                temp.next = new ListNode((l1.val + l2.val + sum)%10);
                sum = (l1.val + l2.val + sum)/10;
                l1 = l1.next;
                l2 = l2.next;
                temp = temp.next;
                
            }
            while(l1 !=null){
                temp.next = new ListNode((l1.val + sum)%10);
                sum = (l1.val+sum)/10;
                l1 = l1.next;
                temp = temp.next;
            }
            while(l2 !=null){
                temp.next = new ListNode((l2.val + sum)%10);
                sum = (l2.val+sum)/10;
                l2 = l2.next;
                temp = temp.next;
            }
            if(sum != 0)
                temp.next=new ListNode(1);
            return res.next;
        }
    }

  • 相关阅读:
    jQuery 上传附件
    SSM框架前台传中文到后台乱码问题的解决办法
    zTree 获取当前节点下所有子节点(包含当前选中的节点)
    jQuery 合并单元格
    Json 字符串排序
    遍历List 删除某条数据
    jquery 遍历页面 class为xxx的td
    MagicSuggest可输可选控件
    ParamQueryGrid绑定数据
    checkbox选中事件
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9591037.html
Copyright © 2011-2022 走看看