zoukankan      html  css  js  c++  java
  • [LeetCode]66、Plus One

    题目描述:

    Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

    You may assume the integer do not contain any leading zero, except the number 0 itself.

    The digits are stored such that the most significant digit is at the head of the list.

    思路:

    大数存储,加一。一个整数,存在一个数组中,最高位在a[0],最低位在a[a.lenth-1].要在末尾+1,如果a[a.lenth-1]<9,则直接加一返回。

    如果等于9,则该位置0,往前一位继续计算。如果最高位仍是9,加一位会导致进位,则变为0,新加一位置1。

     1 public class Solution66 {
     2     public int[] plusOne(int[] digits){
     3         for(int i = digits.length-1;i >= 0;--i){
     4             if(digits[i]<9){
     5                 ++digits[i];
     6                 return digits;
     7             }
     8             else if(digits[i]==9){
     9                 digits[i]=0;
    10             }
    11         }
    12         int[] res = new int[digits.length+1];
    13         res[0] = 1;
    14         return res;
    15     }
    16     public static void main(String[] args) {
    17         // TODO Auto-generated method stub
    18         Solution66 solution66 = new Solution66();
    19         int[] digits = {0};
    20         int[] result;
    21         result= solution66.plusOne(digits);
    22         for(int i = 0; i< result.length;i++){
    23             System.out.print(result[i]);
    24         }
    25     }
    26     
    27 }
  • 相关阅读:
    Sublime Text 3——插件配置篇
    Sublime Text 3——基本介绍篇
    线性同余方程
    费马小定理
    一点心事
    寒诗
    e网通学习笔记
    std::cout<<"Goodbye 2019"<<" "<<"Hello 2020"<<' ';
    新砍
    NOIP2019游记
  • 原文地址:https://www.cnblogs.com/zlz099/p/8144975.html
Copyright © 2011-2022 走看看