zoukankan      html  css  js  c++  java
  • [Leetcode 4] 66 Plus One

    Problem:

    Given a number represented as an array of digits, plus one to the number.

    Analysis:

    The given array represents number from the greatest position to least position, so addition must start from the end of the array; 

    When adding 1 to the number, there're two situations: 1. the digit is 9, then we need to set it to 0 and continue add to the next position; 2. the digit is not 9, then we add 1 to this digit and directly exit;

    One more thing to consider is if all the digits are 9 (e.g. 9, 99, 999, 99999), after adding 1 the result has one more space (e.g. 10, 100, 1000, 100000); we must create a new space to contain the result;

     The time complexity in worst case is 2n, in best cast is 1, in general is O(n), the space complexity is O(n)

    Code:

    public class Solution {
        public int[] plusOne(int[] digits) {
            // Start typing your Java solution below
            // DO NOT write main() function
            //if (digits.length == 0) return 0;
            
            int i;
            for (i=digits.length-1; i>=0; --i) {
                if (digits[i] != 9) {
                    digits[i] += 1;
                    break;
                } else {
                    digits[i] = 0;
                }
            }
            
            if (i < 0) {
                int[] newdigits = new int[digits.length+1];
                newdigits[0] = 1;
                for (int j=0; j<digits.length; j++)
                    newdigits[j+1] = digits[j];
                    
                return newdigits;
            } else
                return digits;
        }
    }

    Attention:

    To new an primitive type array, use new Int[length]  rather than Int(length)

    Can use System.arraycopy(src, pos, des, pos, len) to finish the copy process

  • 相关阅读:
    Objective-C NSString基本使用 类方法 self关键字
    Objective-C 封装 继承 多态
    Objective-C 类和对象
    Objective-C 第一个小程序
    python基础--函数作用域
    python基础--函数1
    python基础--文件操作
    python基础--集合
    python基础--字典
    python基础--列表,元组
  • 原文地址:https://www.cnblogs.com/freeneng/p/3002400.html
Copyright © 2011-2022 走看看