LeetCode 66. Plus One

分析

难度 易

来源

https://leetcode.com/problems/plus-one/description/

题目

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

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

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

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
解答
 1 package LeetCode;
 2 
 3 public class L66_PlusOne {
 4     public int[] plusOne(int[] digits) {
 5         int len=digits.length;
 6         int[] result=new int[len+1];
 7         /*for(int i=0;i<result.length;i++){
 8             System.out.println(result[i]);
 9         }
10         System.out.println(result);*/
11         int carry=1;//加1
12         for(int i=len-1;i>=0;i--){//数组最高位表示数字低位,从最高位开始算
13             digits[i]+=carry;
14             if(digits[i]==10){
15                 digits[i]=0;
16                 carry=1;//向前进位
17             }else
18                 carry=0;
19         }
20         if(carry==1){
21             result[0]=carry;
22             for(int i=0;i<len;i++){
23                 result[i+1]=digits[i];
24             }
25             return result;
26         }else
27             return digits;
28     }
29     public static  void main(String[] args){
30         L66_PlusOne l66=new L66_PlusOne();
31         int[] digits={9,8,7,6,5,4,3,2,1,0};
32         int[] result=l66.plusOne(digits);
33         for(int i=0;i<result.length;i++){
34             System.out.print(result[i]);
35         }
36     }
37 }

 

 

posted on 2018-10-18 09:24 flowingfog 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/flowingfog/p/9808615.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值