zoukankan      html  css  js  c++  java
  • leetcode 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         ListNode temp1,temp2;
    15         temp1=l1;
    16         temp2=l2;
    17         int flag=0;
    18         int sum=0,v1=0,v2=0;
    19         ListNode res=new ListNode(-1);
    20         ListNode curr=res;
    21         while (temp1!=null || temp2!=null) {
    22             if (temp1==null) {
    23                 v1=0;
    24             }else {
    25                 v1=temp1.val;
    26             }
    27             if (temp2==null) {
    28                 v2=0;
    29             }else {
    30                 v2=temp2.val;
    31             }
    32             sum=v1+v2+flag;
    33             if (sum>=10) {
    34                 sum=sum-10;
    35                 flag=1;
    36             }else {
    37                 flag=0;
    38             }
    39             ListNode node=new ListNode(sum);
    40             curr.next=node;
    41             curr=curr.next;
    42             if (temp1!=null) {
    43                 temp1=temp1.next;
    44             }
    45             if (temp2!=null) {
    46                 temp2=temp2.next;
    47             }
    48         }
    49         if (flag>0) {
    50             curr.next=new ListNode(1);
    51         }
    52         return res.next;
    53     }
    54 }
  • 相关阅读:
    TypesScript+Webpack
    TypeScript 类型
    git操作
    kafka
    java: cannot find symbol symbol: variable log
    Angular结构型指令,模块和样式
    Angular 自定义拖拽指令
    Angular changeDetction
    Angular 依赖注入
    RXJS Observable的冷,热和Subject
  • 原文地址:https://www.cnblogs.com/birdhack/p/4106680.html
Copyright © 2011-2022 走看看