plus-one
来源:互联网 发布:软件设计师考试经验 编辑:程序博客网 时间:2024/06/07 12:01
packagecom.ytx.array;
/**
* plus-one
*
* Given a number represented as an
* array of digits, plus one to the number.
*
*@authoryuantian xin
* 给你一个用数组表示的数,求加一之后的结果,结果还是用数组表示。
*
* 思路:因为数组最后一位为个位,先从数组最后一位开始处理,从后往前处理,如果
* 是数字9,加1要进位,如果全都数组里存的都是9,比如9999,那么,数组需要扩容,变成10000。
*/
publicclassPlus_one {
publicint[] plusOne(int[]digits) {
intlen = digits.length;
if(digits== null || len == 0) return null;
//进位标志和加上1
intadd = 1;
//数组从后往前处理
for(inti = len -1; i >= 0; i--) {
intsum=digits[i] +add;
digits[i] = sum % 10;//如果进位了,sum=10,求余为0
add= sum / 10; //同时更新 add,没用进位add=0,有进位add = 1;
//如果循环过程中add = 0,则后续不可能有进位了,数组也不需要扩容,直接终止循环
if(add== 0) break;
}
//如果add经过整个循环还是add = 1,说明每一位都是9,数组需要扩容。
if(add== 1) {
int[]ans = newint[len+ 1];
ans[0] = 1;
for(inti = 1; i < len + 1; i++) {
ans[i] = digits[i- 1];
}
returnans;
}
return digits;
}
publicstaticvoidmain(String[] args) {
int[]data= {9,9,9,9};
int[] ans = new Plus_one().plusOne(data);
for(inti = 0; i < data.length+ 1; i++) {
System.out.print(ans[i]);
}
}
}
阅读全文
0 0
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- Plus One
- CodeForces 620E New Year Tree 线段树
- 破解IntelliJ Idea
- 【博览网】C++标准库——第三周课程笔记
- 控件定位学习:radio、checkbox、ComboBox
- shiro实现session共享
- plus-one
- python---布尔类型赋值,字符串,len(),转义、拼接、替换、文件操作
- 第2章 开始VBA编程的第一步。
- 文章标题
- 端口大全
- SpringMVC token 防止表单重复提交
- A*B Problem II
- convert-sorted-array-to-binary-search-tree
- RN环境配置