Leetcode 66.Plus One

作者: 沉默的叔叔 | 来源:发表于2016-12-05 09:50 被阅读141次

题目


Plus One

题目大意:将一个数字加1,这个数字的每一位存放在数组里。

直接模拟相加的过程就好。

代码如下:

public class Solution {
    public int[] plusOne(int[] digits) {
        boolean flag = true;//标记有没有进位
        for (int i = digits.length-1;i>=0;i--){
            //小于9说明没有进位,直接加1后跳出循环
            if(digits[i]<9){
                digits[i] = digits[i] + 1;
                break;
            } else {
                //有进位则继续检查前一位
                digits[i] = 0;
                //第一位有进位
                if (i == 0) {
                    flag = false;
                }
                continue;
            }
        }
        if (flag)
            return digits;
        else {
            //第一位有进位的时候数组最前边要加1
            int[] re = new int[digits.length+1];
            re[0] = 1;
            for (int i=1;i<re.length;i++)
                re[i] = digits[i-1];
            return re;
        }
    }
}

相关文章

  • Leetcode 66.Plus One

    题目 题目大意:将一个数字加1,这个数字的每一位存放在数组里。 直接模拟相加的过程就好。 代码如下:

  • 66.Plus One

    Given a non-empty array of digits representing a non-nega...

  • TestDrive

    One LeetCode Everyday Will solve one LeetCode Problem eve...

  • [easy][Array]66.Plus One

    原题是: Given a non-negative integer represented as a non-em...

  • LeetCode 66-70

    66. Plus One[https://leetcode-cn.com/problems/plus-one/] ...

  • 66. Plus One

    66. Plus One 题目:https://leetcode.com/problems/plus-one/ 难...

  • 568. Maximum Vacation Days

    LeetCode wants to give one of its best employees the opti...

  • 2019-02-01

    LeetCode 233. Number of Digit One Description Given an in...

  • 66. 加一

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

  • Maximum Vacation Days

    题目LeetCode wants to give one of its best employees the op...

网友评论

    本文标题:Leetcode 66.Plus One

    本文链接:https://www.haomeiwen.com/subject/nirhmttx.html