码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 66. Plus One(加1)

时间:2017-07-23 10:10:14      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:exce   blank   simple   ==   lead   ++   目标   length   sel   

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 public class Solution 
 2 {
 3     public int[] plusOne(int[] digits) 
 4     {
 5         // check param validation.
 6         if(digits == null || digits.length == 0)
 7             return null;
 8         
 9         int size = digits.length;
10         
11         // iterate from right to left.
12         for(int i= size-1; i>=0; i--)
13         {
14             if(digits[i] < 9)    // just add 1 and return digits array.
15             {
16                 digits[i]++;
17                 return digits;
18             }
19             else    
20                 digits[i] = 0;
21             
22         }
23         
24         // it comes here, meaning the 1 hasn‘t been added.
25         int[] res = new int[size+1];
26         res[0] = 1;        // add 1 to the most left digit and all rest digits are 0.
27         
28         return res;
29     }
30 }

参考资料:

https://discuss.leetcode.com/topic/24288/my-simple-java-solution

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

LeetCode 66. Plus One(加1)

标签:exce   blank   simple   ==   lead   ++   目标   length   sel   

原文地址:http://www.cnblogs.com/jimmycheng/p/7223474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!