• [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

  • 相关阅读:
    ArcSDE安装报 “contains an incorrect path”
    vs对话框"发生生成错误,是否继续并运行上次的成功生成"的设置
    修改XML节点名称
    git 常用
    mysql 执行sql流程
    DocumentBuilderFactory.newInstance() 异常解决
    samba 配置
    ajax jquery
    c++ map
    javacc jjtree 写法 以及 jj写法 基本语法 以及应用
  • 原文地址:https://www.cnblogs.com/freeneng/p/3002400.html
Copyright © 2020-2023  润新知