Plus one

作者: Gressil | 来源:发表于2015-11-12 18:09 被阅读19次

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.
用一个数组表示一个非负整数的每一位,写一个函数返回这个整数+1的结果。
比如

input [9,9,9,9] 
return[1,0,0,0,0]

题目比较简单,看到就很容易直接写出来,比如我写的是这样:

public int[] plusOne(int[] digits) {
        int mod = 0,carry = 1, sign = digits[0];
        for (int i = digits.length-1; i >= 0; i--) {
            int temp = digits[i]+carry;
            mod = temp%10;
            carry = temp/10;
            digits[i] = mod;
        }
        if (carry == 0) {
            return digits;
        }else {
            int temp[] = new int[digits.length+1]; 
            temp[0] = carry;
            for (int i = 1; i < temp.length; i++) {
                temp[i] = digits[i-1];
            }
            return temp;
        }
    }

这么写结果倒是没什么问题,也通过了所有的测试,不过看到别人的代码才知道自己的代码实在是拖泥带水。下面是别人家孩子的代码。思路清晰,而且少了一次循环。

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

写出干净的代码是在需要多加练习,清晰的思路是关键,继续加油。

相关文章

  • 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/ 难...

  • Plus One

    https://leetcode.com/problems/plus-one/description/ 思路 反向...

  • Plus One

  • one plus

    Easy, Math Question 一个数以digit序列的形式给出,加一返回对应digit序列 Notes ...

  • Plus One

    Given a non-negative number represented as an array of di...

  • plus one

    question: answer: 之前蠢了,打印数组用Arrays.toString()方便很多直接在Syste...

  • Plus one

    Given a non-negative number represented as an array of di...

  • Plus one

    Given a non-negative number represented as an array of di...

  • Plus One

    题目描述Given a non-empty array of digits representing a non-...

网友评论

    本文标题:Plus one

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