1

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.

3
  • Why do you want it to be more efficient? How do you use it? Do you have performance tests that have showed that it is too slow? If not, don't optimize it. Commented Mar 9, 2015 at 17:34
  • 1
    well, why don't you just print them backwards from char[] arr? Commented Mar 9, 2015 at 17:34
  • Why you would it to be more efficient? You can use a standard for-loop and loop through the char array backward; with an arraylist pre-allocated with the size of the char array (if you need a list). Otherwise if it's just for printing: while(num != 0) { println(num % 10); num /= 10; } Commented Mar 9, 2015 at 17:34

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome way, I think this is just what I need:D
2

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]);
}

1 Comment

Thanks for your answer, in fact, the first guide about this question is to print them backwards, there must be some other more efficient ways, please just ignore this.
2

If by "more efficient" you mean fewer lines, you could use:

char[] reversed = new StringBuilder(String.valueOf(num))
                             .reverse().toString().toCharArray();

1 Comment

Thanks for your answer, but "more efficient" means compute more quickly:)
1

Simplest way:

long num = 123456789;

StringBuilder sb=new StringBuilder(num+"");

System.out.println(""+sb.reverse());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.