首页 > 代码库 > [leetcode] Plus One
[leetcode] Plus One
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.
https://oj.leetcode.com/problems/plus-one/
思路:大数计算的思想,注意carry的处理。如果最高位进位需要重新分配数组空间。
import java.util.Arrays;public class Solution { public int[] plusOne(int[] digits) { if (digits == null || digits.length == 0) return digits; int n = digits.length; int i; int c = 1; for (i = n - 1; i >= 0; i--) { if (c == 0) break; digits[i] += c; if (digits[i] > 9) { digits[i] -= 10; c = 1; } else c = 0; } if (c == 1) { int[] newDigits = new int[n + 1]; newDigits[0] = 1; for (i = 0; i < n; i++) newDigits[i + 1] = digits[i]; return newDigits; } else return digits; } public static void main(String[] args) { System.out.println(Arrays.toString(new Solution().plusOne(new int[] { 1, 9, 9 }))); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。