I'm learning java coming from a ruby background and self-teaching.
I am doing a problem that wants a number reversed and listed into an array by digit.
Ex 1234 -> [4,3,2,1]
In ruby I did this easily -
def digitize(n)
n.to_s.reverse.split("").map(&:to_i)
end
In java, my code is not working, because clearly, I am doing something wrong.
public class Kata {
public static int[] digitize(long n) {
String s = String.valueOf(n);
String r = reverse(s, s.length()-1);
String[] array = r.split("");
Float[] floats = Arrays.stream(array).map(Float::valueOf).toArray(Float[]::new);
}
return floats;
}
Is there a simpler way to do this with built-in methods like ruby? I tried doing everything separately. First variable s , I wanted to convert the number to a string. Second variable r , reversing that string. Third variable array , splitting the variable r into digits. Floats at the end was to convert the array of strings to digits.
public class Kata {
public static int[] digitize(long n) {
String numStr = String.valueOf(n);
int digits[] = new int[numStr.length()];
int counter = 0;
for(int i = numStr.length() - 1; i >= 0; i--) {
digits[i] = Integer.parseInt(Character.toString(numStr.charAt(counter++)));
}
return digits;
}
}
Your method returns Float[]
instead of int[]
. Try this:
int[] ints = Arrays.stream(array).mapToInt(Integer::parseInt).toArray();
return ints;
Use the JDK:
int[] reversedDigits = Arrays.stream(new StringBuilder().append(n).reverse().toString().split("(?<=.)")).mapToInt(Integer::parseInt).toArray();
Not as terse as ruby. A little embarrassing actually, but 1 line nevertheless.
You could collect a List
and then reverse
it with Collections.reverse(List)
and then convert that to an int[]
. Something like,
public static int[] digitize(long n) {
String s = String.valueOf(n);
List<Integer> al = s.chars().map(ch -> Character.digit(ch, 10))
.boxed().collect(Collectors.toList());
Collections.reverse(al);
return al.stream().mapToInt(Integer::intValue).toArray();
}
or exploit the String.length()
to build the array directly like
public static int[] digitize(long n) {
String s = String.valueOf(n);
int[] out = new int[s.length()];
IntStream.range(0, s.length()).forEach( //
i -> out[i] = Character.digit(s.charAt(s.length() - i - 1), 10));
return out;
}
or combine that with a map
for the even shorter
public static int[] digitize(long n) {
String s = String.valueOf(n);
return IntStream.range(0, s.length()) //
.map(i -> Character.digit(s.charAt(s.length() - i - 1), 10)).toArray();
}
This works for me.
import java.lang.StringBuffer;
public class Kata {
public static float[] digitize(long n) {
int[] ints= new StringBuffer(n.toString()).reverse().toString().split("(?!^)").mapToInt(Integer::parseInt).toArray();;
return ints;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.