例如爲int n = 1234
我可以創建一個字符串(s.valueOf(n))
,那麼我會定義數組是這樣的:如何爲一個數字的數字(int)數組分配內存,其長度等於該數字的位數?
int[] array = new int[s.length()]; //this allocates memory for an array with 4 elements
是否有任何其他方式做到這一點不使用字符串,只有整數?
例如爲int n = 1234
我可以創建一個字符串(s.valueOf(n))
,那麼我會定義數組是這樣的:如何爲一個數字的數字(int)數組分配內存,其長度等於該數字的位數?
int[] array = new int[s.length()]; //this allocates memory for an array with 4 elements
是否有任何其他方式做到這一點不使用字符串,只有整數?
您可以使用Math#log10查找位數。
numOfDigits = (int)(Math.log10(n)+1);
現在你這樣做:
int[] array = new int[numOfDigits];
注意,如果n = 1999
,numOfDigits
將4.所以你分配爲4個整數的內存,而不是1999年的整數。
但要小心,而讀取的方法的文檔,你會注意到:
如果參數是正零或負零,那麼結果是 負無窮大。
+1對於n> 0,這是正確的:) – 2013-05-07 10:14:29
如果最後需要整數上近似值,則日誌有點矯枉過正。 – 2013-05-07 10:21:53
我假設你正在談論Java,所以:
int value = myValue;
for (int noOfDigits = 1; Math.abs(value) >= 1; ++noOfDigits) {
value /= 10;
}
int[] array = new int[noOfDigits];
這還不包括爲主導的符號空間,如果是負數,但你可以輕鬆地測試這種情況,並通過一個遞增noOfDigits
。
使用log function
找到沒有。數字。
int size = (int)Math.log10(1234)+1;
int[] array = new int[size];
據我的瞭解,你可以做的數字
int n = 12345;
int count = 1;
while(n>10){
n = n/10;
count++;
}
int[] array = new int[count];
if (n>0){
numberOfDigets = (int)(Math.log10(n)+1);
}
else if (n < 0){
numberOfDigets = (int)(Math.log10(Math.abs(n))+1);
} else {
numberOfDigets = 1;
}
下獲得計數如果n是更大然後爲零用作Maroun Maroun寫的Math.log10功能。如果n小於零,則使用Math.abs函數獲取正數值。如果你想爲 - 加2而不是1分配空間,else子句用於n爲0並且將numberOfDigets設置爲1的情況。
如果對java函數的額外調用無關緊要這段代碼。 (n!= 0){ numberOfDigets =(int)(Math.log10(Math.abs(n))+1);其他{ numberOfDigets = 1; }
Math.abs(n)
將始終返回n的陽性版本。值得注意的是Integer.min_value
因爲價值仍然是消極的,但這是另一個問題。
對不起?你能否詳細說明一下? – Freak 2013-05-07 10:11:44
獲取數字的數字長度是編程學生衆所周知的問題。我相信你可以很快地谷歌。 – SJuan76 2013-05-07 10:12:22
@freak - 我還能說什麼? – constant 2013-05-07 10:12:44