• Plus One Linked List


    Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.

    Example:

    Input:
    1->2->3
    
    Output:
    1->2->4


     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode plusOne(ListNode head) {
    11         List<Integer> temp = new ArrayList<Integer>();
    12         
    13         ListNode move = head;
    14         while(move != null) {
    15             temp.add(move.val);
    16             move = move.next;
    17         }
    18         
    19         int carry = 1;
    20         ListNode last = new ListNode(-1);
    21         for(int i = temp.size() - 1; i >= 0; i--) {
    22             int total = carry + temp.get(i);
    23             last.val = total % 10;
    24             carry = total / 10;
    25             
    26             ListNode pre = new ListNode(-1);
    27             pre.next = last;
    28             last = pre;
    29         }
    30         
    31         if (carry == 1) {
    32             last.val = 1;
    33             return last;
    34         } else {
    35             return last.next;
    36         }
    37     }
    38 }
  • 相关阅读:
    bzoj 1208: [HNOI2004]宠物收养所
    bzoj 1207: [HNOI2004]打鼹鼠
    【NOIP模拟赛】小奇的矩阵
    【NOIP模拟赛】小奇挖矿 2
    Making the Grade POJ
    POJ 3616Milking Time
    [USACO08JAN]电话线Telephone Lines
    Radar Installation POJ
    Warfare And Logistics UVA
    【NOIP2009】最优贸易
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6410454.html
Copyright © 2020-2023  润新知