zoukankan      html  css  js  c++  java
  • LeetCose-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.

    问题:

      问题很简单给出一个非负整数,用数组的方式表示改非负整数,例如321则给出一个三位数组[3][2][1],给该数组加一,返回结果数组。

    分析:

      把两类特殊情况考虑上即可,如[1][9]、[9][9][9]。前者直接进一位,后者需要创建多一位的数组,保存结果。

    public class Solution {
        public int[] plusOne(int[] digits) {
            int length = digits.length;
            int i=0;
            if(digits[length-1]!=9)                             最后一位不是9,直接加1
                digits[length-1]+=1;
            else{
                for(i=length-1;digits[i]==9;i--){         否则从最后一位向前循环找到第一位不是9的
                    if(i==0){                    如果i==0了证明给出的数组都是9为第二种情况
                        int[] result = new int[length+1] ;
                        result[0]=1;
                        for(int j=1;j<=length;j++)
                            result[j]=0;
                        return result;
                    }
                    else{                      否则i!=0的话正常进位
                    digits[i]=0;
                }
            }
            digits[i]+=1;
        }
        return digits;
    }
    }
  • 相关阅读:
    超链接
    Image中的alt
    预格式
    json字符串转json对象,json对象转换成java对象
    google-gson 解析json
    java HTTP请求工具
    JS文件中获取contextPath的方法
    eclipse中安装freemarker插件及ftl使用freemarker编辑器
    MyBatis 传入参数之parameterType
    typeAliases别名
  • 原文地址:https://www.cnblogs.com/zhoujunfu/p/4051685.html
Copyright © 2011-2022 走看看