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;
        }
  • 相关阅读:
    c++面试题
    MFC 字符串类CString 源代码
    c++ ofstream & ifstream文件流操作
    理解ip和端口
    求解最长回文字符串
    @Document元注解的使用
    JVM、JRE和JDK的理解
    Java发展历程及各版本新特性
    Maven的安装配置
    认识Java注解
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4804280.html
Copyright © 2011-2022 走看看