移除 9
难度:
标签:
题目描述
代码结果
运行时间: 32 ms, 内存: 16.4 MB
/*
* LeetCode Problem 660: Remove 9
*
* Problem Statement:
* Start from integer 1, remove all the integers containing 9 such as 9, 19, 29...
* Return the kth number after removing.
*
* Approach using Java Streams:
* 1. Create a stream of integers starting from 1.
* 2. Filter out numbers that contain '9' by converting to string and checking if '9' is present.
* 3. Limit the stream to the kth element.
* 4. Collect the stream to a list and return the last element of the list.
*/
import java.util.stream.IntStream;
public class Remove9Stream {
public int newInteger(int n) {
return IntStream.iterate(1, i -> i + 1)
.filter(i -> !Integer.toString(i).contains("9"))
.limit(n)
.boxed()
.collect(java.util.stream.Collectors.toList())
.get(n - 1);
}
}
解释
方法:
该题解使用递归的方法求解。基本思路是将数字 n 看作 9 进制数,然后将其转换为 9 进制数的十进制表示。在转换过程中,9 会被跳过,最终得到移除了 9 的新整数。递归函数每次处理 n 的一位数字,将其转换为新的整数。
时间复杂度:
O(log n)
空间复杂度:
O(log n)
代码细节讲解
🦆
你是如何确定将数字n转换为9进制数,并且在转换中跳过9这一操作能够正确地移除所有的9?
▷🦆
请问在递归函数中,为什么将n除以9后的结果再递归处理?这样做的目的是什么?
▷🦆
在递归的过程中,为何选择将结果乘以10再加上n%9,这种操作的数学逻辑是什么?
▷🦆
递归结束的条件是n为0,这种设计有没有可能导致对极小或者特定数字处理时的边界问题?
▷