leetcode — plus-one

本文介绍了一个简单而实用的算法,用于将一个非负整数(以数组形式给出,最高位在数组开头)加一。通过逆序遍历数组进行逐位加法,并处理进位情况,最终返回新的整数数组。文章提供了完整的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Source : https://oj.leetcode.com/problems/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.
 *
 */
public class PlusOne {

    /**
     * 加法运算,注意进位
     *
     * @param digit
     * @return
     */
    public Integer[] plusOne (int[] digit) {
        int carry = 1;
        List<Integer> result = new ArrayList<Integer>();
        for (int i = digit.length - 1; i > -1; i--) {
            carry += digit[i];
            result.add(0, carry % 10);
            carry = carry / 10;
        }
        if (carry > 0) {
            result.add(0, carry);
        }
        return result.toArray(new Integer[result.size()]);
    }


    public static void main(String[] args) {
        PlusOne plusOne = new PlusOne();
        int[] arr = new int[]{1,2,3};
        int[] arr1 = new int[]{1,9,9};
        int[] arr2 = new int[]{9,9,9};
        int[] arr3 = new int[]{1};
        int[] arr4 = new int[]{9};
        int[] arr5 = new int[]{};

        System.out.println(Arrays.toString(plusOne.plusOne(arr)));
        System.out.println(Arrays.toString(plusOne.plusOne(arr1)));
        System.out.println(Arrays.toString(plusOne.plusOne(arr2)));
        System.out.println(Arrays.toString(plusOne.plusOne(arr3)));
        System.out.println(Arrays.toString(plusOne.plusOne(arr4)));
        System.out.println(Arrays.toString(plusOne.plusOne(arr5)));
    }
}

转载于:https://www.cnblogs.com/sunshine-2015/p/7679446.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值