[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 }

 

转载于:https://www.cnblogs.com/zlz099/p/8144975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值