Plus One leetcode java
2015-12-16 16:47
555 查看
问题描述:
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.
分析:非负整数,存储在数组中。the most significant digit 最高位存储在列表的第一个,例如:98, array[0] 存储9,array[1]存储8。
定义变量carry存储进位,遍历数组,每次修改digits[i] 与 carry
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.
分析:非负整数,存储在数组中。the most significant digit 最高位存储在列表的第一个,例如:98, array[0] 存储9,array[1]存储8。
定义变量carry存储进位,遍历数组,每次修改digits[i] 与 carry
public int[] plusOne(int[] digits) { if(digits == null || digits.length == 0) return null; int len = digits.length; int carry = 0; //进位,只借用一个变量,不需要数组 for(int i = len - 1; i >= 0; i--){ if(i == len - 1){ carry = (digits[i] + 1 ) / 10; //进位 digits[i] = (digits[i] + 1 ) % 10; //本位 } else { int digit = (digits[i] + carry) % 10; //本位 carry = (digits[i] + carry) / 10; //进位 digits[i] = digit; } } if(carry == 0) return digits; else { int[] new_digits = new int[len + 1]; for (int i = 1; i < new_digits.length; i++) { new_digits[i] = digits[i - 1]; } new_digits[0] = carry; return new_digits; } }
相关文章推荐
- 详解Java解析XML的四种方法—DOM/SAX/jdom/dom4j
- Java API —— JDK5新特性
- my eclipse 删除项目时报这个错,An exception has been caught while processi
- struts2_06 struts2补充,值栈,属性驱动与模型驱动
- JAVA Sokcet(服务端)连接WebSocket个人总结
- 老李分享:JAVA性能监控工具
- 老李分享:《Java Performance》笔记2——JVM命令行选项及垃圾收集日志解析 2
- 老李分享:《Java Performance》笔记2——JVM命令行选项及垃圾收集日志解析 1
- struts_05 各种验证器,ognl表达式,struts2常用标签,防止表单重复提交,jfreeChart插件的运用
- 老李分享:《Java Performance》笔记1——性能分析基础 2
- 老李分享:《Java Performance》笔记1——性能分析基础 1
- Java多线程总结(4)— 线程范围内数据操作的隔离及ThreadLocal类
- struts2_04 常见servlet对象的获取,文件上传
- struts2_03 自定义类型转换器 拦截器
- Spring下面的@Transactional注解标志的讲解
- struts2_02
- struts2_01
- Java获取当前日期的前一个月,前一天的时间
- java处理url中的特殊字符%等
- Struts2框架搭建