leetcode解题方案--066--Plus One

来源:互联网 发布:碳谱数据库 编辑:程序博客网 时间:2024/06/05 05:34

题目

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

分析

数组的末尾加1
考虑进位数组长度也有可能变

class Solution {    public static int[] plusOne(int[] digits) {        int add = 0;        int sum = digits[digits.length-1] + 1;        digits[digits.length-1] = sum%10;        add = sum/10;        int index = digits.length-2;        while (add!=0 && index>=0) {            digits[index] = digits[index]+1;            if (digits[index] == 10) {                add = 1;                digits[index] = 0;            } else {                add = 0;            }            index--;        }        if (add!=0) {            int[] ret = new int[digits.length+1];            System.arraycopy(digits, 0, ret,1,digits.length);            ret[0] = add;            return ret;        }        return digits;    }}
原创粉丝点击