【LeetCode】Plus One 解题报告

【LeetCode】Plus One 解题报告

[LeetCode]

https://leetcode.com/problems/plus-one/

Total Accepted: 99274 Total Submissions: 294302 Difficulty: Easy

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.

Ways

就是把一个数组表示的整数+1,看起来非常简单的一个题目。但是据说是Google最喜欢的面试题。

首先,我想到的第一个方法就是把这个数组转化成字符串,再把字符串转化为整数,+1之后再转化为数组。太麻烦了!而且代码提交之后发现了溢出情况,就是说给的一个数的位数特别多,一个int表示不了了。所以只能使用乖乖的方法吧。

想法是从最后一位开始看,如果这位是9的话转为0,不是的话就+1,再往前面看,直到不是9为止。

运算结束之后,如果最高位为0,说明这个数所有的位数都为9,那么需要创建新数组,把最高位置为一。

这个想法的确实是一个加法最基本的想法。说明我们需要从最常见的事物中找到准确表达的算法。

public class Solution {
    public int[] plusOne(int[] digits) {
        for(int i=digits.length-1; i>=0; i--){
            if(digits[i]==9){
                digits[i]=0;
                continue;
            }else{
                digits[i]+=1;
                break;
            }
        }

        if(digits[0]==0){
          int[] answer=new int[digits.length + 1];
            answer[0]=1;
            return answer;
        }else{
            return digits;
        }
    }
}

AC:0ms

Date

2016 年 05月 8日

你可能感兴趣的:(LeetCode)