LeetCode 66. Plus One
来源:互联网 发布:显卡超频软件哪里 编辑:程序博客网 时间:2024/06/03 12:55
66.Plus One
题意: 用一个非空数组来代替一个非负数,给这个整数+1.假设这个非空数组第一位不为0,除非0本身。
原题意: 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.
题意不是很好理解,简单举例说明题意,如果输入数组为[1,2,3],看作整数123,加1位124,输出数组[1,2,4],如果输入数组为[9,9],看作整数99,加1为100,输出数组为[1,0,0].
我的解法: 考虑特殊情况,就是原本这个数的所有位数全为9,加1后,数组长度比之前+1.
public int[] plusOne(int[] digits) { for(int i = digits.length - 1; i >= 0; i--){ if(digits[i] == 9){ digits[i] = 0; } else{ digits[i]++; break; } } if(digits[0] != 0){ return digits; } else{ int[] newDigits = new int[digits.length + 1]; newDigits[0] = 1; return newDigits; }}
第二种解法: 思路与第一种一样,换一种角度。
public int[] plusOne1(int[] digits) { int n = digits.length; for(int i=n-1; i>=0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] newNumber = new int [n+1]; newNumber[0] = 1; return newNumber;}
阅读全文
0 0
- [LeetCode]66.Plus One
- LeetCode --- 66. Plus One
- [Leetcode] 66. Plus One
- [leetcode] 66.Plus One
- [leetcode] 66. Plus One
- Leetcode-66. Plus One
- 【leetcode】66. Plus One
- 66. Plus One LeetCode
- 【LeetCode】66. Plus One
- [LeetCode]66. Plus One
- 【LeetCode】66. Plus One
- LeetCode 66. Plus One
- LeetCode *** 66. Plus One
- leetcode 66. Plus One
- 【leetcode】66. Plus One
- leetcode 66. Plus One
- [LeetCode]66. Plus One
- Leetcode 66. Plus One
- 前端通过JS将从后端接口返回的大数求和的简单实现
- SpringBoot入门总结
- 《深度学习:21天实战Caffe》第一天
- Kaggle入门
- C语言(如何不使用第三个变量达到交换两个变量值的目的)
- LeetCode 66. Plus One
- Google Guava 缓存实现接口的限流
- setContentView中的源码探索(未修订)
- SpringMVC学习笔记(二)-----配置文件
- 中东美食!
- CentOS7配置VNC
- Ubuntu安装JDK详解
- 第一个任务
- PAT 甲级 1027. Colors in Mars (20)