zoukankan      html  css  js  c++  java
  • LeetCode 66. Plus One(加1)

    Given a non-negative integer represented as a non-empty array 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.


    题目标签:Array

      这道题目给了我们一个digits 的array, 这个array 等于一个数字,让我们加1。来分析一下,如果是不需要进位的 <9 , 那么直接加1就返回。如果是需要进位的,=9, 那么我们需要把目前的digit 改为0,接着继续检查前一位,因为你不确定前一位加1 是不是需要进位。一旦当我们找到不需要进位的那个digit, 加1 返回就可以了。如果碰到一种极端的情况,类似于 999 的话,那么我们 遍历完之后 是 000, 还需要一个1 ,所以要重新建立一个array, size + 1,把1 加在 [0]的位置。

    Java Solution:

    Runtime beats 39.20% 

    完成日期:04/05/2017

    关键词:Array

    关键点:特殊情况类似于999 需要重新建立一个array with size + 1 来放1在最左边

     1 class Solution 
     2 {
     3     public int[] plusOne(int[] digits) 
     4     {
     5         int[] res;
     6         
     7         // iterate digits from right to left
     8         for(int i= digits.length - 1; i>=0; i--)
     9         {
    10             if(digits[i] == 9) // digit = 9
    11             {
    12                 digits[i] = 0;
    13             }
    14             else // digit from 0 to 8
    15             {
    16                 digits[i]++; 
    17                 return digits; // after add 1 to digit, return 
    18             }
    19                 
    20         }
    21         
    22         // coming here means the 1 is not yet added and also digits is finished
    23         // there is only one case: 999...
    24         res = new int[digits.length + 1];
    25         res[0] = 1;
    26         
    27         
    28         return res;
    29     }
    30 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    成熟失去快乐
    明天出发
    不知其期
    不是自己的机子就是不好
    都收拾完了
    文盲
    郁闷
    好像感冒了
    又都疯了
    流水账,从我开始接触计算机时写起
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7223474.html
Copyright © 2011-2022 走看看