LeetCode刷题实战66:加一
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 加一,我们先来看题面:
https://leetcode-cn.com/problems/plus-one/
Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
题意
例题
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。
解题
class Solution {
public int[] plusOne(int[] digits) {
int carry = 1;
for (int i = digits.length - 1; i >= 0; i--) {
if (carry == 0) {
return digits;
}
int tmp = digits[i] + carry;
carry = tmp / 10;
digits[i] = tmp % 10;
}
if (carry != 0) {
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}
return digits;
}
}
上期推文: