算法的重要性,我就很少說了吧,想去大廠,就必需要通過基礎知識和業務邏輯面試+算法面試。因此,爲了提升你們的算法能力,這個號後續天天帶你們作一道算法題,題目就從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