lintcode 加一(Plus One )(Java)
来源:互联网 发布:类似origin的软件 编辑:程序博客网 时间:2024/04/30 15:16
1.题目详情
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.
给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。
该数字按照大小进行排列,最大的数在列表的最前面。
2.样例
给定 [1,2,3] 表示 123, 返回 [1,2,4].
给定 [9,9,9] 表示 999, 返回 [1,0,0,0].
3.分析
本来的思路是转化为string->int->int[],这个念头一闪而过我就感觉不对了,可能是潜意识里每次碰到处理数字的都想转string处理,后来做的题多了发现这种想法一般都是错的。
正确思路分析:如果数组的最后一位不是9的话,那么直接最后一位自身增加1返回数组即可;如果碰到是9的情况,则需要考虑进位的情况,从后往前遍历循环,如果为为9则赋值为0,前一位加1,如果不为9则加一返回,或者循环结束,如果循环结束还没有return,则可以判断每位都是9,则可以全赋值为0,前面增加一个1。
4.代码
public class Solution { /** * @param digits a number represented as an array of digits * @return the result */ public int[] plusOne(int[] digits) { // Write your code here int n = digits.length; for (int i = n - 1; i >= 0; i--){ if (digits[i] == 9){ digits[i] = 0; }else { digits[i]++; return digits; } } //创建一个新数组,长度加1 int[] result = new int[n + 1]; result[0] = 1; return result; }}
阅读全文
0 0
- lintcode 加一(Plus One )(Java)
- Plus One 加一
- (LeetCode)Plus One --- 加一
- Plus One【加一】【容易】
- leetcode Plus One 加一
- 【LeetCode-面试算法经典-Java实现】【066-Plus One(加一)】
- LeetCode 66 Plus One(加一)(vector)
- leetcode:Plus One (加一)【面试算法题】
- LeetCode OJ 之 Plus One (加一)
- 407.Plus One-加一(容易题)
- leetcode 66. Plus One-加一
- LeetCode-66-Plus One(加一操作)
- 66. Plus One 加一运算
- leetcode 66. Plus One加一
- [Lintcode]Plus One
- LintCode 407:Plus One
- 加一(LintCode)
- LeetCode 66. Plus One(加1)
- RDS SQL Server
- 何时使用copy,strong,weak,assign关键字 定义属性
- gcc编译系统
- 启动resin报错:Error runningnewResin: Can't find neither 'server' nor 'server-default' nor 'server-multi'
- pandas基础介绍
- lintcode 加一(Plus One )(Java)
- Java门面模式(或外观模式)
- bzoj 3505 数三角形 组合数 解题报告
- RecyclerView瀑布流如何动态计算imageview的宽高
- android 引导页的制作
- SAP审批策略相关表
- 开发中常见小问题(笔记)
- 对接 PDA 问题件扫描确认上架
- Python中的下划线'_'用法