zoukankan      html  css  js  c++  java
  • LeetCode(66): Plus one

    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.

    Subscribe to see which companies asked this question.

    题意:给定一个数组,数组中的数字在0~9之间,这个数组表示为一个整数。排列顺序为:最高位在array[0] ,最低位在[n-1],n为数组长度。例如:34,存储为array[0]=3,array[1]=4。题目要求对这个数字进行加1操作。

    解题思路:从数组的最后一位开始加1,如果为9加1之后为10,产生进位,则该位置0,进位;如果加1之后不产生进位则结束;如果最后到[0]位之后仍然产生进位则,需要新建一个长度为(n+1)的数组,拷贝原来的数组。

    代码:

    public int[] plusOne(int[] digits) {
            
            if(digits[digits.length-1] <9){
                digits[digits.length-1] += 1;
                return digits;
            }
            //是否进位
            boolean carry = true;
            for(int i = digits.length - 1;i>=0;i--){
                if(!carry){
                    break;
                }
                if(digits[i]==9){
                    carry = true;
                    digits[i]=0;
                }else{
                    digits[i] += 1;
                    carry =false;
                }
                } //for
            if(carry){
                int[] result = new int[digits.length + 1];
                System.arraycopy(digits,0,result,1,digits.length);
                result[0] = 1;
                return result;
            }else{
            return digits;
            }

    其中:用到的java中的数组Copy的函数System.arraycopy()完成将一个数组的内容复制到另一个数组中

    public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    参数含义:

    • src -- 这是源数组.

    • srcPos -- 这是源数组中的起始位置。

    • dest -- 这是目标数组。

    • destPos -- 这是目标数据中的起始位置。

    • length -- 这是一个要复制的数组元素的数目。

  • 相关阅读:
    How to deploy the ASP.NET MVC 3 website into the IIS7 on Windows server 2008
    NHibernate Notes3_How to set a default value of column
    NHibernate Notes2_Handling versioning and concurrency
    block定义与使用
    记住
    监听键盘高度
    超出父视图区域的点击相应
    监听键盘高度变化
    iOS开发上线升级流程
    NSTimer理解
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5102088.html
Copyright © 2011-2022 走看看