zoukankan      html  css  js  c++  java
  • [LeetCode]66. 加一(数组)

    题目

    给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

    最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

    你可以假设除了整数 0 之外,这个整数不会以零开头。

    示例 1:

    输入: [1,2,3]
    输出: [1,2,4]
    解释: 输入数组表示数字 123。
    示例 2:

    输入: [4,3,2,1]
    输出: [4,3,2,2]
    解释: 输入数组表示数字 4321。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/plus-one
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题解

    对于不需要最高位进位的,直接break;
    否则,一定是999-》1000的情况,直接最高位置1,后面不用管。

    代码

    class Solution {
        public int[] plusOne(int[] digits) {
            for(int i=digits.length-1;i>=0;i--){
                digits[i]++;
                if(digits[i]==10){
                    digits[i]=0;
                }
                else{
                    return digits;
                }
            }
            int[] digitsNew=new int[digits.length+1];
            digitsNew[0]=1;
            return digitsNew;
        }
    }
    
  • 相关阅读:
    Python-Matplotlib 12 多图figure
    Python-Matplotlib 11 子图-subplot
    Python Day16
    Python Day15
    Python Day13-14
    Python Day12
    Python Day11
    Python Day9-10
    Python Day8
    Python Day8
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/13179940.html
Copyright © 2011-2022 走看看