首页 > 其他 > 详细

Plus One 解答

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