zoukankan      html  css  js  c++  java
  • Add Two Numbers

    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

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    14         if(null == l1)
    15             return l2;
    16         if(null == l2)
    17             return l1;
    18         ListNode head = new ListNode(0);
    19         ListNode ptr = head;
    20         int carry = 0;                                            //进位
    21         while(null != l1 && null != l2){
    22             ListNode temp = new ListNode(l1.val + l2.val);
    23             temp.next = null;
    24             ptr.next = temp;
    25             ptr = ptr.next;
    26             l1 = l1.next;
    27             l2 = l2.next;
    28         }
    29         while(null != l1){
    30             ListNode temp = new ListNode(l1.val);
    31             ptr.next = temp;
    32             temp.next = null;
    33             ptr = ptr.next;
    34             l1 = l1.next;
    35         }
    36         while(null != l2){
    37             ListNode temp = new ListNode(l2.val);
    38             ptr.next = temp;
    39             temp.next = null;
    40             ptr = ptr.next;
    41             l2 = l2.next;
    42         }
    43         //开始进位    
    44         ptr = head.next;
    45         while(null != ptr){
    46             ptr.val = ptr.val + carry;
    47             carry = ptr.val / 10;
    48             ptr.val %= 10;
    49             ptr = ptr.next;
    50         }
    51         if(1 == carry){
    52             ptr = head.next;
    53             while(null != ptr.next)
    54                 ptr = ptr.next;
    55             ListNode temp = new ListNode(1);
    56             temp.next = null;
    57             ptr.next = temp;
    58         }
    59         
    60         return head.next;
    61     }
    62 }
  • 相关阅读:
    面向对象 委托
    面向对象 继承 接口
    C# 面向对象 , 类与对象
    C# 知识点回顾
    SQL 数据库知识点回顾
    C# 10 总复习
    spring boot jpa 表关联查询分组 group by 去重
    钉钉新增考勤组 设置考勤规则
    elasticsearch 学习之父子关联查询 parent/child
    Elasticsearch 查询学习
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4120646.html
Copyright © 2011-2022 走看看