2012-04-17 106 views
1

我寫這樣的:有沒有更好的(更快)的方法來將數字分成數字?

void blah(int num) 
{ 
    int numOfDigits = Math.log10(num); 
    int arr[] = new int[numOfDigits + 1]; 
    for(int i = numOfDigits; i>0; i--) 
    { 
     arr[i] = num%10; 
     num = num/10; 
    } 
} 

但我認爲必須有這樣做的更優雅的方式。在那兒?如果你想從這個去int[]

String[] arr = Integer.toString(num).split("(?<=\\d)"); 

int[] arrint = new int[arr.length]; 
for (int i = 0; i < arr.length; i++) 
    arrint[i] = Integer.parseInt(arr[i]); 
+0

這個方法不起作用 - 這是馬車。你需要從i = numOfDigits - 1開始; – 2012-04-17 00:27:58

+0

可能的重複[有沒有在j2se或雅加達的公共資源,這將數字轉換爲數組數組?](http://stackoverflow.com/questions/1213375/is-there-something-in-j2se-or-jakarta -commons-thats-converted-a-number-to-an-arra) – 2012-04-17 00:28:02

+0

@EugeneRetunsky:對不起,這是一個錯字。 – noMAD 2012-04-17 00:29:36

回答

2

如果你滿意的字符串,你可以這樣做然後使用string.toCharArray()並轉換回來。根據您的世界觀,這可能會也可能不會更「優雅」。

+0

是基於RegEx的分隔符? – noMAD 2012-04-17 00:31:17

+0

yes - split()使用正則表達式來分割。 '(?<= \\ d)'表示「前一個字符是一個數字」。我測試了它,它能正常工作 – Bohemian 2012-04-17 00:32:16

+0

這是否比問題使用的循環方法更快(忽略了一些問題)? – 2012-04-17 00:43:01

0

考慮整數轉換爲使用Integer.toString字符串

+0

你不能投射不同類型的數組:() – Bohemian 2012-04-17 00:30:02

+0

@波希米亞感謝,修正。 – cmh 2012-04-17 00:31:19

+0

是的,這就是我的想法。你能詳細說一下'轉換回來的部分嗎?' – noMAD 2012-04-17 00:37:12

0

這可能是一個辦法(我不看好這個超級驕傲:))

Integer number = 1234567890;    // input number 
String temp = number.toString();   // convert to string 
int [] output = new int[temp.length()]; 

for (int i=0 ; i< temp.length(); i++)  // get character at index i from string 
    output[i] = temp.charAt(i) - '0';  // convert it to number by removing '0' 
相關問題