Javascript 这个NumberComplement函数的时间复杂度是多少?
函数NumberComplement(num)获取一个十进制数,将其转换为二进制数,然后将每个二进制数反转,然后将反转后的二进制数转换回十进制数 我的解决办法是Javascript 这个NumberComplement函数的时间复杂度是多少?,javascript,algorithm,time-complexity,Javascript,Algorithm,Time Complexity,函数NumberComplement(num)获取一个十进制数,将其转换为二进制数,然后将每个二进制数反转,然后将反转后的二进制数转换回十进制数 我的解决办法是 NumberComplement(num){ let bin= num.toString(2).split('').map( x => 1-x ).join('') return parseInt(bin,2) } 此函数的时间复杂度是多少?为什么 (让我困惑的部分是map函数,其中num已经从一个整数转换为一个由0和1组成的数
NumberComplement(num){
let bin= num.toString(2).split('').map( x => 1-x ).join('')
return parseInt(bin,2)
}
此函数的时间复杂度是多少?为什么
(让我困惑的部分是map函数,其中num已经从一个整数转换为一个由0和1组成的数组,我们知道数组的长度是log(num)+1,因此该函数迭代log(num)+1次,这使得时间复杂度为O(log(n))?……还是我想得太多了?仅仅是O(n)
非常感谢您花了这么多时间!让我们先假设
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渐近时间复杂度,即O(1)
让我们假设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渐近时间复杂度O(1)
它是O(1)
…@zerkms为什么它是常量?我正在将num转换为一个数组,并在整个数组中迭代…..它的上限是每次拆分
,映射
和加入
@zerkms谢谢!我现在得到了它…在谷歌搜索了JS中最大的精确整数值后…它是O(1)
…@zerkms为什么它是常量?我正在将num转换为一个数组,并在整个数组中迭代…它的上限是每次拆分
,映射
和加入
@zerkms谢谢!我现在得到了它…在谷歌搜索了JS中最大的精确整数值之后。。。