【LeetCode】066.Plus One

来源:互联网 发布:淘宝做什么产品赚钱 编辑:程序博客网 时间:2024/06/08 14:25

题目:

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.

解答:

考虑进位问题,从后往前遍历,低于9直接加上1并且返回,否则一直往前进位。最高位进位后需要新生成一个数组。

代码:

public class Solution {    public int[] plusOne(int[] digits) {if (digits == null || digits.length == 0)return null;int index = digits.length - 1;while (index >= 0) {if (digits[index] < 9) {digits[index] += 1;return digits;} else {digits[index] = 0;index--;}}int[] ret = new int[digits.length + 1];if (index < 0) {ret[0] = 1;for (int i = 0; i < digits.length; i++) {ret[i + 1] = digits[i];}}return ret;}}


0 0