美文网首页
leetcode-加一

leetcode-加一

作者: Pei丶Code | 来源:发表于2018-08-30 11:28 被阅读15次

加一
给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。
最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
最开始想法:**超出int范围了
class Solution {
public int[] plusOne(int[] digits) {//129
int count = digits.length;//3
int num = 0;
for(int i = 0; i<count ;i++){
//
num = num +digits[i]
(int)Math.pow(10,count-i-1);
}
num = num+1;//130
String s = String.valueOf(num);
int count1 = s.length();//3
int[]array = new int[count1];
// array[1] = num;
for(int j = 0;j<count1;j++){
// 130/100 = 1...30
int a = num/(int)Math.pow(10,count1-j-1);
num = num%(int)Math.pow(10,count1-j-1);
array[j] = a;
}
return array;
}
}

网上解法:
class Solution {
public int[] plusOne(int[] digits) {//129
if (digits.length == 0) return digits;
int carry = 1, n = digits.length;
for (int i = digits.length - 1; i >= 0; --i) {
if (carry == 0) return digits;
int sum = digits[i] + carry;
digits[i] = sum % 10;
carry = sum / 10;
}
int[] res = new int[n + 1];
res[0] = 1;
return carry == 0 ? digits : res;

}

}

相关文章

  • LeetCode-加一

    给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放在数组的首位, 数组中每个元素只存...

  • leetcode-加一

    加一给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。最高位数字存放在数组的首位, 数组中每个...

  • leetcode- 加一

    给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 最高位数字存放在数组的首位, 数组中每个元素只...

  • LeetCode-加一

    题目链接 => 戳这里 解法:这道题其实有点像两数相加那道题

  • 【leetcode-动态规划】Longest Increasin

    【leetcode-动态规划】Longest Increasing Subsequence 给定一个无序的整数数组...

  • leetcode-数组-加一|Plus One(Python3)

    给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。 最高位数字存放在数组的首位, 数组中每个元...

  • 一起学算法-69. x 的平方根

    一、题目 LeetCode-算法入门-69. x 的平方根地址:https://leetcode-cn.com/p...

  • LeetCode-股票问题

    LeetCode-股票问题 121. 买卖股票的最佳时机[https://leetcode-cn.com/prob...

  • 算法—字符串编码

    题目: 字符串编码(LeetCode-中等) 编码规则为: k[encoded_string],表示其中方括号内部...

  • 【leetcode-动态规划】零钱兑换

    【leetcode-动态规划】零钱兑换 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来...

网友评论

      本文标题:leetcode-加一

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