Leetcode---Plus one carry array

Source: Internet
Author: User

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

The digits is stored such, the most significant digit was at the head of the list.

Problem-solving ideas: integers plus 1, you need to consider whether the carry and the final result will be more than one, such as 99,999 such a situation.

Package Leedcode;

public class PlusOne {

    private static int[] plus (int[] digits) {
        if (digits.length==0| | Digits==null) return digits;
        for (int i = digits.length-1; I >= 0; i--) {//loop essentially replaces carry
            digits[i] = digits[i] + 1;
            if (digits[i] = = ten)
                digits[i] = 0;
            else
                return digits;
        }
        Int[] res= new Int[digits.length + 1];
        Res[0] = 1;
        return res;
    }

    public static void Main (string[] args) {
        int[] tes = {9, 9};
        int[] res = plus (tes);
        for (int i = 0; i < res.length; i++) {
            System.out.print (Res[i] + "");}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.