首页 > 其他 > 详细

Plus One

时间:2016-07-11 00:54:55      阅读:275      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!