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         }

  • 相关阅读:
    Matlab中imagesc用法
    codevs 3160 最长公共子串(SAM)
    spoj 7258 SUBLEX(SAM,名次)
    spoj 1812 LCS2(SAM+DP)
    spoj 8222 Substrings(后缀自动机+DP)
    tyvj P1519 博彩游戏(AC自动机+DP滚动数组)
    bzoj 1030 [JSOI2007]文本生成器(AC自动机+DP)
    vijos P1459 车展(Treap,中位数)
    bzoj 3196 Tyvj 1730 二逼平衡树(线段树套名次树)
    bzoj 1483 [HNOI2009]梦幻布丁(链表+启发式合并)
  • 原文地址:https://www.cnblogs.com/springfor/p/3888002.html
Copyright © 2011-2022 走看看