函数NumberComplement(num)取一个十进制数,将其转换为二进制数,然后反转每个二进制数,然后将反转的二进制数转换回十进制数。
我的解决方案是
InternalLoggerFactory.setDefaultFactory(new Log4J2LoggerFactory());
这个函数的时间复杂度是什么?为什么?
(困惑我的部分是map函数,其中num已经从一个整数转换为由0和1组成的数组,我们知道数组的长度是log(num)+1,所以函数迭代log(num)+1次,这使得时间复杂度为O(log(n))?........或者我是否过度思考它?它只是O(n)?
非常感谢您的时间!
答案 0 :(得分:3)
让我们假设num
可以进入无穷大。然后,您将涉及这些函数调用:
| Function | Asymptotic time complexity | Motivation |
|--------------|----------------------------|------------------------------------------------------------------------------------------------------|
| .toString(2) | O(log n) | Number of bits in num |
| .split | O(log n) | Number of characters from .toString, which is equal to number of bits in num |
| x => 1-x | O(1) | x is either 0 or 1 so this does not vary with the size of n |
| .map | O(log n) | The anonymous function applied to each element in the result from .split: O(1) * O(log n) = O(log n) |
| .join | O(log n) | Number of characters in the result from .map, which is equal to the number of bits in num |
| .parseInt | O(log n) | Number of characters in bin, which is equal to the number of bits in num |
添加它们:
.toString + .split + .map + .join + .parseInt =
O(log n) + O(log n) + O(log n) + O(log n) + O(log n) =
O(log n)
但在Javascript中并非如此,整数的上限为53位。在n
的上限,您总是得到O(1)
的Big-O渐近时间复杂度。