LeetCode(066) Plus One (Java)

来源:互联网 发布:电子商务平台软件下载 编辑:程序博客网 时间:2024/06/06 01:22

题目如下:

Plus One Total Accepted: 42505 Total Submissions: 138460 My Submissions Question Solution 
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.


分析如下:

一开始写居然写出来了 ArrayIndexOutOfBoundsException尴尬 数组下标越界。

虽然这道题目木比较简答,但是可能会有一些扩展的问题。见这里CodeGanker分析. 

我自己在Google的电面中就遇到了这道题,我觉得为什么Google喜欢的原因是后续可以问一些比较基本的扩展问题,比如可以扩展这个到两个数组相加,或者问一些OO设计,假设现在要设计一个BigInteger类,那么需要什么构造函数,然后用什么数据结构好,用数组和链表各有什么优劣势。这些问题虽然不是很难,但是可以考到一些基本的理解,所以平时准备有机会还是可以多想想哈


我的代码:

// 209 mspublic class Solution {    public int[] plusOne(int[] digits) {        int carry = 1;        for (int i = digits.length - 1; i >= 0; --i) {            int new_carry = (digits[i] + carry)/10;            digits[i] = (digits[i] + carry) % 10;            carry = new_carry;                    }        if (carry > 0){            int[] array = new int [digits.length + 1];            //for (int i = array.length -1; i >=0; --i) {               //     array[i] = digits[i - 1];            //java.lang.ArrayIndexOutOfBoundsException: 1                        for (int i = array.length -1; i >=1; --i) {                array[i] = digits[i - 1];            }            array[0] = carry;            return array;        }else {            return digits;        }    }}


0 0
原创粉丝点击