Plus One
来源:互联网 发布:ubuntu和优麒麟 编辑:程序博客网 时间:2024/06/06 13:57
题目地址:https://leetcode.com/problems/plus-one/
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.
题目说只有非负数,这个题目的难度将下降不少。题目本身没啥难度,关键是处理好进位即可:
input: {9,9,9,9}output: {1,0,0,0,0}input: {0,0,9,9,9,9}output: {0,1,0,0,0,0}
处理好这两种情况就没啥难的了:
public class PlusOne { public static int[] plusOne(int[] digits) { for (int i = digits.length - 1; i >= 0; i--) { boolean carry = false; int val = digits[i] + 1; if (val < 10) { digits[i] = val; break; } else { digits[i] = val - 10; if (i == 0) { int[] r = new int[digits.length + 1]; int[] c = {1}; System.arraycopy(c, 0, r, 0, c.length); System.arraycopy(digits, 0, r, c.length, digits.length); return r; } continue; } } return digits; } public static void main(String[] args) { int[] digits = {0, 0, 9,9,9,9,9}; System.out.println(Arrays.toString(digits)); System.out.println(Arrays.toString(plusOne(digits))); }}
感觉第二种测试案例不太合理,虽说不为错,但是至少得出结果得把前面高位的0去掉。
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
- Tomcat、Servlet、JDK三者的支持关系
- TCP/IP层次模型
- 探秘中东直播市场
- php配置redis扩展
- 分享一个Migo2.0企业级电商项目Demo ssm redis mysql dubbo 分布式部署 涵盖大量电商技术
- Plus One
- Codeforces Round #384 (Div. 2)
- latex基本操作
- Codeforces Round #384(Div. 2)D. Chloe and pleasant prizes【树形dp】
- php获取内容第一张图片
- 大龄程序员的发展方向是做管理还是继续写程序
- c语言实现大小端判断和二进制模式写入各种数据到文件
- java虚拟机
- 生活中有太多的悲哀誰都無法預測未來