首页 > 其他 > 详细

LeetCode -- Plus One

时间:2015-09-14 19:14:41      阅读:195      评论: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.

 

Analysis:

一个非负数字由一个数组表示,然后对这个数字加一。

这个题目主要是需要考虑特殊情况:数字全部都是9;数字中有某几位是9;一般情况。所以把所有情况考虑到就ok。

 

Answer:

public class Solution {
    public int[] plusOne(int[] digits) {
        if(digits == null)
            return null;
        if(digits[digits.length-1] != 9) {
            digits[digits.length-1] ++;
            return digits;
        }
        boolean flag = true;
        for(int i=0; i<digits.length; i++) {
            if(digits[i] != 9) {
                flag = false;
                break;
            }
        }
        if(flag == true) { //所有位数都为9
            int[] res = new int[digits.length + 1];
            res[0] = 1;
            return res;
        }
        else { //最后一位为9
            for(int i=digits.length-1; i>=0; i--) {
                if(digits[i] == 9)
                    digits[i] = 0;
                else {
                    digits[i] ++;
                    return digits;
                }
            }
        }
        return digits;
    }
    
}

 

LeetCode -- Plus One

原文:http://www.cnblogs.com/little-YTMM/p/4807937.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!