• Plus One 解答


    Question

    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.

    Solution

    To solve this problem, we can use a flag to mark if the current digit needs to be changed.

    Time complexity O(n), space cost O(n)

     1 public class Solution {
     2     public int[] plusOne(int[] digits) {
     3         int length = digits.length;
     4         int[] result = new int[length + 1];
     5         int flag = 1;
     6         for (int i = length - 1; i >= 0; i--) {
     7             if (flag == 1) {
     8                 if (digits[i] < 9) {
     9                     digits[i] += 1;
    10                     flag = 0;
    11                 } else {
    12                     digits[i] = 0;
    13                 }
    14             }
    15         }
    16         if (flag == 1) {
    17             for (int i = 0; i < length; i++)
    18                 result[i + 1] = digits[i];
    19             result[0] = 1;
    20             return result;
    21         }
    22         return digits;
    23     }
    24 }
  • 相关阅读:
    expdp使用
    sed命令(二)
    linux的sed命令(一)
    weblogic找不到数据源
    windows 常用操作
    Spring in action (1)
    Eclipse使用
    maven
    Maven-01 安装maven
    Java开发环境搭建
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4799830.html
Copyright © 2020-2023  润新知