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


    解题思路:

    先对原数组进行处理。从数组最后一位开始往前检查,如果当前数字是<9的,说明你加1无需进位,从循环跳出即可,如果当前数字等于9,说明加1涉及进位,且加1后当前数字应记为0,继续循环处理。

    当对原数组处理完后,还需要判断当前第0位是不是已经变为0了,如果已经变为0了说明是类似99+1这种,需要进位。其他则不需要。

    一般对数字进行操作的题都要考虑边界,尤其是溢出问题。


    Java code:

    public int[] plusOne(int[] digits) {int len = digits.length;
            for(int i=len-1; i>=0; i--){
                if(digits[i] < 9) {
                    digits[i]++;
                    break;
                }else{
                    digits[i] = 0;
                }
            }
            
            int[] newdigits;
            if(digits[0] == 0){
                newdigits = new int[len+1];
                newdigits[0] = 1;
                for(int i = 1; i< newdigits.length;i++) {
                    newdigits[i] = digits[i-1];
                }
                return newdigits;
            }
            return digits;
        }

    Reference:

    1. http://www.cnblogs.com/springfor/p/3888002.html

  • 相关阅读:
    c# 使用 Read 读取数据块
    C# TCP/IP通信,Socket通信例子
    c# virtual 关键字 虚方法
    统计图
    oauth2.0 判断接口是否允许跨域
    OI常用模板合集
    CSP2021游记
    8.16 树上问题模拟赛总结
    8.15 图论模拟赛垫底记
    8.14 字符串模拟赛总结
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4827826.html
Copyright © 2011-2022 走看看