资讯专栏INFORMATION COLUMN

leetcode 66 Plus One

ytwman / 3326人阅读

摘要:题目详情题目的意思是,给你一个用数组表示的一个非负整数。你需要返回这个整数加后,所对应的数组。解法一主要需要关注的点就在于,当末尾数字为的时候的进位情况。如果不需要进位了,则代表循环可以结束了。

题目详情
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.
题目的意思是,给你一个用int数组表示的一个非负整数。你需要返回这个整数加1后,所对应的int数组。
解法一

主要需要关注的点就在于,当末尾数字为9的时候的进位情况。

如果不需要进位了,则代表循环可以结束了。此时直接返回输入的digits数组

如果数组的所有元素都为9,则需要在最前面补一位1,我们应该意识到剩下的位都为0,不需要通过循环赋值,只需要把数组的第一位赋值为1就可以,剩下的元素自然为0

    public int[] plusOne(int[] digits){
        int carry = 1;    
        
        for(int i=digits.length-1;i>=0;i--){
            if(digits[i] + carry == 10){
                digits[i] = 0;
                carry = 1;
            }else{
                digits[i] = digits[i] + carry; 
                return digits;
            }            
            
        }
        
        int[] res = new int[digits.length+1];
        res[0] = 1;
        return res;
        
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67109.html

相关文章

  • leetcode66 将数组表示的非负整数加一

    摘要:题目要求一个非负整数被表示为一个数组,数组中每一个元素代表该整数的一个位。数组的下标越小,代表的位数越高。现在对该数组做加一运算,请返回结果数组。 题目要求:一个非负整数被表示为一个数组,数组中每一个元素代表该整数的一个位。数组的下标越小,代表的位数越高。现在对该数组做加一运算,请返回结果数组。 /** * @author rale * * Given a non-negativ...

    QLQ 评论0 收藏0
  • [Leetcode] Plus One 加一

    摘要:不过这里有个小技巧,因为我们只要加,所以不用完全模拟加法的所有规则一个数如果不是,那加以后不会对其他位产生影响。 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...

    shmily 评论0 收藏0
  • [LeetCode/LintCode] Plus One

    Problem 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. Example Given [1,2...

    sunsmell 评论0 收藏0
  • [LeetCode] Plus One Linked List

    Problem Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer. You may assume the integer do not contain any leading zero, except the number 0 i...

    shiyang6017 评论0 收藏0
  • leetcode部分题目答案之JavaScript版

    摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...

    alphahans 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<