LeetCode:Plus One

来源:互联网 发布:javascript 移除元素 编辑:程序博客网 时间:2024/06/06 17:20

推荐参照:Leetcode题目难度等级及面试频率总结

题目描述:

  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.

题目解释:

  输入的数组digits表示一个大整数,每个表示一位,给这个大整数加1,返回结果。(ps.一开始没读明白题目的意思…囧)

思路一:

  从结尾处开始计算(废话),如果小于9,直接+1,结束循环;否则,将该位置为0,继续循环,直到小于9。最后判断第一位是不是0,如果为0,表示第一位应该进位,其他位都为0。

public class Solution {    public int[] plusOne(int[] digits) {        int n = digits.length;        for(int i = n - 1; i >= 0; i--){            if(digits[i] < 9){                digits[i] += 1;                break;            }            else                digits[i] = 0;        }        if(digits[0] == 0){            int [] newDigits = new int [n+1];            /*for(int i = 0; i < n; i++){//没必要,声明的时候默认为0                newDigits[i+1] = 0;            }*/            newDigits[0] = 1;            return newDigits;        }        return digits;    }}

思路二:

  Java在java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算。BigDecimal所创建的是对象,我们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而必须调用其相对应的方法。方法中的参数也必须是BigDecimal的对象。

import java.math.BigDecimal;import java.util.*;public class Solution {    public int[] plusOne(int[] digits) {        String str = "";        for(int n : digits)            str += n;        str = new BigDecimal(str).add(BigDecimal.valueOf(1)).toString();        int [] newDigits = new int [str.length()];        for(int i = 0; i < str.length(); i++)            newDigits[i] = str.charAt(i) - '0';        return newDigits;    }}

Any comments greatly appreciated.

1 0
原创粉丝点击