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

Plus One 解答

时间:2015-09-11 06:45:53      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

Question

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.

Solution

To solve this problem, we can use a flag to mark if the current digit needs to be changed.

Time complexity O(n), space cost O(n)

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         int length = digits.length;
 4         int[] result = new int[length + 1];
 5         int flag = 1;
 6         for (int i = length - 1; i >= 0; i--) {
 7             if (flag == 1) {
 8                 if (digits[i] < 9) {
 9                     digits[i] += 1;
10                     flag = 0;
11                 } else {
12                     digits[i] = 0;
13                 }
14             }
15         }
16         if (flag == 1) {
17             for (int i = 0; i < length; i++)
18                 result[i + 1] = digits[i];
19             result[0] = 1;
20             return result;
21         }
22         return digits;
23     }
24 }

Plus One 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4799830.html

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