题目
给出一个随机数(long),您必须以相反的顺序在数组中返回此数字的数字。
例:
348597 => [7,9,5,8,4,3]
测试用例:
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class DigitizeExampleTests {
@Test
public void tests() {
assertArrayEquals(new int[] {1, 3, 2, 5, 3}, Kata.digitize(35231));
}
}
解题
My
public class Kata {
public static int[] digitize(long n) {
char[] arrChar = String.valueOf(n).toCharArray();
int[] arrInt = new int[arrChar.length];
for (int i = 0; i < arrChar.length; i++) {
arrInt[i] = Integer.parseInt(String.valueOf(arrChar[arrChar.length-i-1]));
}
return arrInt;
}
}
Other
public class Kata {
public static int[] digitize(long n) {
return new StringBuilder().append(n)
.reverse()
.chars()
.map(Character::getNumericValue)
.toArray();
}
}
import java.lang.Math;
public class Kata {
public static int[] digitize(long n) {
String s = String.valueOf(n);
int length = s.length();
int[] array = new int[length];
for ( int i = 0; i < length; i++){
array[i] = (int) (s.charAt(length - i - 1)) - 48;
}
return array;
}
}
这方法也还不错。
后记
一拿到这题就知道,答案肯定不唯一,我的代码还可以优化,嘎嘎。
public static int[] digitize(long n) {
String m = String.valueOf(n);
int[] arrInt = new int[m.length()];
for (int i = 0; i < m.length(); i++) {
arrInt[i] = m.charAt(m.length() - i - 1) - 48;
}
return arrInt;
}
网友评论