[英]How to reverse a number more efficiently with Java
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? 有人可以建议我用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. 这几乎是Long.toString() 内部执行的操作 ,因此它应该比使用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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.