zoukankan      html  css  js  c++  java
  • [leetcode] 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.

    例如:98,存储为:array[0]=9; array[1]=8。

    思路:从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为 digits.length + 1 的数组,拷贝原数组到该数组中。

    JAVA代码:

    public int[] plusOne(int[] digits) {
            if (digits == null || digits.length == 0) {
                return null;
            }
            int top = 0;
            int flag = 1;
            int i = digits.length - 1;
            int[] tmp = null;
            while (i >= 0) {
                if (top > 0) {
                    int sum = digits[i] + top;
                    if (sum >= 10) {
                        top = 1;
                        digits[i] = sum - 10;
                    }
                    else {
                        digits[i] = sum;
                        top = 0;
                    }
                }
                if (flag == 1) {
                    int sum = digits[i] + 1;
                    if (sum >= 10) {
                        top = 1;
                        digits[i] = sum - 10;
                    }
                    else {
                        digits[i] = sum;
                    }
                    flag = 0;
                }
                if (top == 0) {
                    break;
                }
                else {
                    i --;
                }
            }
            if (top > 0) {
                tmp = new int[digits.length + 1];
                tmp[0] = top;
                for (int j = 1; j < tmp.length; j++) {
                    tmp[j] = digits[j - 1];
                }
            }
            return tmp == null ? digits : tmp;
        }
  • 相关阅读:
    排座椅
    关于math.h的问题
    客户调查
    排队打水
    删数游戏
    小数背包
    零件分组
    桐桐的组合
    桐桐的数学游戏
    桐桐的全排列
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4804280.html
Copyright © 2011-2022 走看看