本文主要是介绍leetcode解题方案--066--Plus One,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
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;}
}
这篇关于leetcode解题方案--066--Plus One的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!