zoukankan      html  css  js  c++  java
  • 66. Plus One

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.


     
    翻译:一个非负整数被表示为非空数组,给该整数加1.
    除了0自己,其它整数都不以0开头
    最高位存储在列表的最前面
     
    大神答案
    public int[] plusOne(int[] digits) {
            
        int n = digits.length;
        for(int i=n-1; i>=0; i--) {
            if(digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            
            digits[i] = 0;//如果前面没有跳出,说明进位了,进位只能进1,所以这一位只能为0
        }
        
        int[] newNumber = new int [n+1];//若全都进位了,则除了第一位,都为0
        newNumber[0] = 1;
        
        return newNumber;
    }
     
    我的答案
    考虑不仔细,误以为会有如8+7这种,所以选择了取余,其实只能是+1.。。。。。。

    class Solution {
    public int[] plusOne(int[] D) {

    D[D.length-1]++;
    for(int i=D.length-1;i>0;i--){
    if(D[i]>9){
    D[i]=D[i]%10;
    D[i-1]++;
    }
    else
    return D;
    }
    if (D[0]>9){
    int[] N=new int[(D.length+1)];
    N[0]=1;
    for(int i=1;i<D.length+1;i++){
    N[i]=D[i-1]%10;
    }
    return N;
    }

    return D;
    }
    }

  • 相关阅读:
    About Face 摘录
    断言的使用
    C#中值传递和引用传递
    C++技巧之断言Assert
    About Face 一 目标导向设计
    About Face 二 设计行为与形态
    C++中引用传递与指针传递区别
    一个新的时代SoLoMo
    离散数学笔记算法部分
    汪教授的离散数学20110308 谓词与量词2
  • 原文地址:https://www.cnblogs.com/mafang/p/8321388.html
Copyright © 2011-2022 走看看