I wrote some code to reverse a number as below:
long num = 123456789;
char[] arr = String.valueOf(num).toCharArray();
List<Character> characterList = new ArrayList<Character>();
for (char c : arr) {
characterList.add(c);
}
Collections.reverse(characterList);
for (Character c : characterList) {
System.out.println(c);
}
output:
9
8
7
6
5
4
3
2
1
Could anyone advise me a more efficient way to achieve this with Java?
EDIT :
In fact, the first guide about this question is to print them backwards, please just ignore this way.
Why use chars? You can do it directly using integer operations:
public static void main(String[] args) {
long num = 123456789;
while (num != 0) {
System.out.println(num % 10);
num = num / 10;
}
}
Output:
9
8
7
6
5
4
3
2
1
This is pretty much what Long.toString() does internally , so it should be more efficient than working with the String.
You can go with only one loop:
long num = 123456789;
char[] arr = String.valueOf(num).toCharArray();
for(int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
If by "more efficient" you mean fewer lines, you could use:
char[] reversed = new StringBuilder(String.valueOf(num))
.reverse().toString().toCharArray();
Simplest way:
long num = 123456789;
StringBuilder sb=new StringBuilder(num+"");
System.out.println(""+sb.reverse());
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.