算法的重要性,我就很少说了吧,想去大厂,就必需要通过基础知识和业务逻辑面试+算法面试。因此,为了提升你们的算法能力,这个号后续天天带你们作一道算法题,题目就从LeetCode上面选 !git
今天和你们聊的问题叫作 加一,咱们先来看题面:面试
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.ide
You may assume the integer does not contain any leading zero, except the number 0 itself.code
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。element
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;
}
}leetcode