zoukankan      html  css  js  c++  java
  • [LintCode] 904. 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

    Example1

    Input: 1 -> 2 -> 3 -> null
    Output: 1 -> 2 -> 4 -> null
    Explanation:
    123 + 1 = 124


    /**
     * Definition for ListNode
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    
    public class Solution {
        /**
         * @param head: the first Node
         * @return: the answer after plus one
         */
        public ListNode plusOne(ListNode head) {
            // Write your code here
            ListNode newHead = reverse(head);
            ListNode cur = newHead;
            
            int carry = 1;
            while (cur != null) {
                int tmp = cur.val + carry;
                carry = tmp / 10;
                cur.val = tmp % 10;
                cur = cur.next;
            }
            if (carry != 0) {
                head.next = new ListNode(1);
            }
            return reverse(newHead);
        }
        
        private ListNode reverse(ListNode head) {
            ListNode prev = null, nxt = null;
            while (head != null) {
                nxt = head.next;
                head.next = prev;
                prev = head;
                head = nxt;
            }
            return prev;
        }
    }
  • 相关阅读:
    js对象
    _proto_和prototype区别
    手写自己的Vuex
    limitPNG压缩图片
    swiper兼容性ie浏览器出现的问题
    postcss-pxtorem
    【Other】Win10防火墙放行Docker(WSL2)端口
    docker容器内使用apt-get报错
    docker+mysql
    docker部署+验证码错误
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12496772.html
Copyright © 2011-2022 走看看