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

    【思路】

    数组从后往前遍历,加一如果不需要进位的话直接返回加一后的结果,需要进位的话继续向前遍历。如果最前面一位需要进位,则生成一个第一位为1,其他位为0,长度加一的新数组。代码如下:

     1 public class Solution {
     2     public int[] plusOne(int[] digits) {
     3         if(digits==null || digits.length==0) return digits;
     4         int i;
     5         for(i = digits.length - 1; i >= 0; i--){
     6             if(digits[i] + 1 < 10){
     7                 digits[i] += 1;
     8                 break;
     9             }
    10             else digits[i] = 0;
    11         }
    12         if(i < 0){
    13             int[] newdigits = new int[digits.length+1];
    14             newdigits[0] = 1;
    15             return newdigits;
    16         }
    17         return digits;
    18     }
    19 }
  • 相关阅读:
    多表查询,连表查询
    mysql数据概念难点
    mysql练习题
    linux下 redis
    nginx安装
    八皇后问题 OpenJ_Bailian
    Prime Ring Problem hdu-1016 DFS
    Oil Deposits hdu-1241 DFS
    Highways
    畅通工程再续
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5511581.html
Copyright © 2011-2022 走看看