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

Plus One

时间:2016-07-11 00:57:45      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

Given a non-negative number represented as an array of digits, plus one to the number.

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

Example

Given [1,2,3] which represents 123, return [1,2,4].

Given [9,9,9] which represents 999, return [1,0,0,0].

分析:

这题分两种情况,一种情况是+1后array size 不变,另一种情况是array size 变大了。怎么知道array size会变大呢,就是当我们已经从尾部来到头部,但是carryover却还是1.

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         if (digits == null || digits.length == 0) return digits;
 4 
 5         int carryover = 1;
 6         int i = digits.length - 1;
 7         int digit = 0;
 8         do {
 9             digit = carryover + digits[i];
10             carryover = digit / 10;
11             digit = digit % 10;
12             digits[i] = digit;
13             i--;
14         } while(carryover == 1 && i >= 0); 
15         // array contains only 9s
16         if (carryover == 1) {
17             int[] newArray = new int[digits.length + 1];
18             newArray[0] = 1;
19             return newArray;
20         }
21         return digits;
22     }
23 }

 

Plus One

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5658840.html

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