zoukankan      html  css  js  c++  java
  • Plus One leetcode java

    题目

    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这种,需要进位。其他则不需要。

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

    代码如下:

     1 public int[] plusOne(int[] digits) {
     2             int length;
     3             length = digits.length;
     4             for(int i = length-1; i>=0; i--){
     5                 if(digits[i]<9){
     6                     digits[i]++;
     7                     break;
     8                 }else{
     9                     digits[i]=0;
    10                 }
    11             }
    12             
    13             int[] newdigits;
    14             if(digits[0]==0){
    15                 newdigits = new int[digits.length+1];
    16                 newdigits[0]=1;
    17                 for(int i=1;i<newdigits.length;i++){
    18                     newdigits[i]=digits[i-1];
    19                 }
    20             }else{
    21                 newdigits = new int[digits.length];
    22                 for(int i=0;i<digits.length;i++){
    23                     newdigits[i]=digits[i];
    24                 }
    25             }
    26              return newdigits;
    27         }

     另外一种考虑溢出的解法如下:

     1       public int[] plusOne(int[] digits) {
     2             for(int i=digits.length-1;i>=0;i--){
     3                 digits[i] =1+digits[i];
     4                 
     5                 if(digits[i]==10)
     6                     digits[i]=0;
     7                 else
     8                     return digits;
     9             }
    10 
    11             //don't forget over flow case
    12             int[] newdigit = new int[digits.length+1];
    13             newdigit[0]=1;
    14             for(int i=1;i<newdigit.length;i++){
    15                 newdigit[i] = digits[i-1];
    16             }
    17             return newdigit;
    18         }

  • 相关阅读:
    在Windows中,U盘或者移动硬盘关不掉时,怎么知道是被哪个程序占用了呢?
    选择的文件中包含不支持的格式
    FTO Obesity Variant Circuitry and Adipocyte Browning in Humans
    SNPsnap | 筛选最佳匹配的SNP | 富集分析 | CP loci
    PhastCons | 序列保守性打分
    hg19基因组 | 功能区域 | 位置提取
    投稿SCI杂志 | 如何撰写cover letter | 如何绘制illustrated abstract
    variant的过滤 | filtering and prioritizing genetic variants
    会议录音的处理 | 提高音量 + 降噪 + 自动添加字幕
    小型数据工作站 | 管理和维护 | Jupyter | Rstudio server | Mac & Win10
  • 原文地址:https://www.cnblogs.com/springfor/p/3888002.html
Copyright © 2011-2022 走看看