[英]How do I make this have a space complexity of O(1) instead of O(n)?
I'm trying to convert a decimal into binary number using iterative process. 我正在尝试使用迭代过程将十进制转换为二进制数。 How can I make this have a space complexity of O(1) instead of O(n)?
如何使它的空间复杂度为O(1)而不是O(n)?
int i = 0;
int j;
int bin[] = new int[n]; //n here is my paramater int n
while(n > 0) {
bin[i] = n % 2;
n /= 2;
i++;
}
//I'm reversing the order of index i with variable j to get right order (e.g. 26 has 11010, instead of 01011)
for(j = i -1; j >= 0; j--) {
System.out.print(bin[j]);
}
First, you don't need place for n
bits if the value itself is n
. 首先,如果值本身是
n
,则不需要放置n
位。 You just need log2(n)+1
. 您只需要
log2(n)+1
。 It won't give you wrong results to use n
bits, but for big values of n
, the memory available to your Java process might be not enough. 使用
n
位不会给您错误的结果,但是对于较大的n
值,您的Java进程可用的内存可能不够。
And, about O(1)
... maybe not really what you were thinking, but: 而且,关于
O(1)
...可能不是您真正想的那样,但是:
Javas int
has a specific fixed value range, which leads to the guarantee that a (positive) int
value needs max 31 bit (if you have negative numbers too, storing the sign somewhere is necessary, that's bit 32). Javas
int
具有特定的固定值范围,这保证了(正) int
值最多需要31位(如果您也有负数,则必须将符号存储在某个地方,即32位)。
With that information, strictly speaking, you can get O(1) just by rewriting your loops so that they loop exactly 31 times. 严格来说,有了这些信息,您只需重写循环即可获得O(1),这样它们就可以准确地循环31次。 Then, for each value of
n
, your code has exactly the same amount of steps, and that is O(1)
per definition. 然后,对于每个
n
值,您的代码具有完全相同的步骤数,即每个定义为O(1)
。
Going the bit fiddling route won't help here. 走一点摆弄路线在这里无济于事。 There are some useful shortcuts if your values fulfil certain conditions, but if you want your code to work with any int value, the normal loop as you have here is likely the best you can get.
如果您的值满足某些条件,则可以使用一些有用的快捷方式,但是如果您希望代码使用任何int值,则此处的普通循环可能是您所能获得的最佳结果。
(Of yourse, CPU intrinsics may help, but not for Java...) (就您而言,CPU内在函数可能有所帮助,但对于Java却没有帮助...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.