LeetCode:Plus One
来源:互联网 发布:javascript 移除元素 编辑:程序博客网 时间:2024/06/06 17:20
推荐参照:Leetcode题目难度等级及面试频率总结
题目描述:
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
题目解释:
输入的数组digits表示一个大整数,每个表示一位,给这个大整数加1,返回结果。(ps.一开始没读明白题目的意思…囧)
思路一:
从结尾处开始计算(废话),如果小于9,直接+1,结束循环;否则,将该位置为0,继续循环,直到小于9。最后判断第一位是不是0,如果为0,表示第一位应该进位,其他位都为0。
public class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for(int i = n - 1; i >= 0; i--){ if(digits[i] < 9){ digits[i] += 1; break; } else digits[i] = 0; } if(digits[0] == 0){ int [] newDigits = new int [n+1]; /*for(int i = 0; i < n; i++){//没必要,声明的时候默认为0 newDigits[i+1] = 0; }*/ newDigits[0] = 1; return newDigits; } return digits; }}
思路二:
Java在java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算。BigDecimal所创建的是对象,我们不能使用传统的+、-、*、/等算术运算符直接对其对象进行数学运算,而必须调用其相对应的方法。方法中的参数也必须是BigDecimal的对象。
import java.math.BigDecimal;import java.util.*;public class Solution { public int[] plusOne(int[] digits) { String str = ""; for(int n : digits) str += n; str = new BigDecimal(str).add(BigDecimal.valueOf(1)).toString(); int [] newDigits = new int [str.length()]; for(int i = 0; i < str.length(); i++) newDigits[i] = str.charAt(i) - '0'; return newDigits; }}
Any comments greatly appreciated.
1 0
- LeetCode: Plus One
- LeetCode Plus One
- [Leetcode] Plus One
- LeetCode: Plus One
- leetcode 33: Plus One
- [LeetCode] Plus One
- [leetCode] Plus One
- 【leetcode】Plus One
- [LeetCode]Plus One
- [leetcode]Plus One
- LeetCode-Plus One
- [leetcode] plus one
- LeetCode - Plus One
- [LeetCode] Plus one
- LeetCode:Plus One
- leetcode之Plus One
- leetcode plus one
- LeetCode | Plus One
- 利用tensorflow搭建CIFAR10 分类网络
- 我的WCF之旅(13):创建基于MSMQ的Responsive Service
- LeetCode笔记:378. Kth Smallest Element in a Sorted Matrix
- Java高并发,如何解决,什么方式解决
- 什么是软件架构
- LeetCode:Plus One
- KVM虚拟化源码分析之KVM_TOOLS(二)
- Java NIO系列教程(一) Java NIO 概述 Channel
- opencv相机标定
- js中数据类型转换的三种方法 重要
- form表单无刷新上传文件
- python爬虫框架-PySpider
- mysql-maxwell binlog订阅
- glib开源库编译过程