Easy-题目30:66. Plus One

来源:互联网 发布:在线美工平台 编辑:程序博客网 时间:2024/06/03 07:27

题目原文:
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.
题目大意:
对用各数位的数组表示一个非负数做+1运算。数组的头部代表数字的高位。
(例如,数字123用数组[1,2,3]表示,加1运算后返回数组[1,2,4])。
题目分析:
分两种情况考虑。
(1) 这个数字全是9,这是一种最特殊的情况,因为新数组的长度跟原来数组不一样。
(2) 其他情况,则仿照竖式加法,从最后一位开始,寻找第一个不是9的数位(一定存在,否则在情况1中已经解决),这一位加1,后面的数位全部置为0.
源码:(language:java)

public class Solution {    public int[] plusOne(int[] digits) {        int len=digits.length;        if(len==0)            return null;        boolean all9=true;        for(int i=0;i<len;i++) {            if(digits[i]!=9) {                all9=false;                break;            }        }        if(all9) { //this num has the form of 999......... , which will be 1000.... after added 1.            int[] result=new int[len+1];            result[0]=1;            return result;        }        else {            if(digits[len-1]<9)                digits[len-1]++;            else {                digits[len-1]=0;                int i=len-2;                while(digits[i]==9)                    digits[i--]=0;                digits[i]++;            }            return digits;        }    }}

成绩:
1ms,beats 4.41%,众数:0ms,58.86%
cmershen的碎碎念:
本题巧用了Java的变量初始化,对整形及整形数组的元素,未赋值的均初始化为0.(不像c中还有什么UVF……dts又乱入了)

0 0
原创粉丝点击