Plus One
来源:互联网 发布:thinkphp sqlserver 编辑:程序博客网 时间:2024/04/28 21:22
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.
题意:一个整数按位存储于一个int数组中,排列顺序为:最高位在array[0] ,最低位在[n-1],例如:98,存储为:array[0]=9; array[1]=8;
解题思路,从数组的最后一位开始加1,需要考虑进位,如果到[0]位之后仍然有进位存在,需要新开一个长度为(n.length + 1)的数组,拷贝原来的数组。
代码如下:
public class Solution { public int[] plusOne(int[] digits) { if(digits==null||digits.length==0) return null; int carry = 1; int sum = 0; int len = digits.length; for(int i=len-1;i>=0;i--){ sum = digits[i]+carry; digits[i] = sum%10; carry = sum/10; } if(carry>0){ int[] a = new int[len+1]; a[0] = carry; for(int i=0;i<len;i++){ a[i+1] = digits[i]; } return a; } return digits; }}
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
- liuling师姐程序学习笔记(1)
- windows sockets 学习 (一)
- “黑马程序员”Java多线程
- 一步一步跟我学习hadoop(2)----hadoop eclipse插件安装和运行wordcount程序
- iOS-UITextField收起键盘和拓展
- Plus One
- Unity Transform 学习和应用
- linux下信号处理机制
- Git 常用命令大全
- Adobe illustrator
- IOS开发之__bridge,__bridge_transfer和__bridge_retained
- archlinux开机挂载分区
- PE结构图
- Swing 自定义控件学习笔记