-6

Can anyone explain to me how to reverse a number start with zero in java. I trying to reverse a number 025 but output is only 52. But output should be 520 explanation much appreciated.

5
  • 3
    please provide your code and what you tried so far Mar 30, 2015 at 7:45
  • 4
    Numeric reversal, I think, is mostly a string operation...
    – npinti
    Mar 30, 2015 at 7:46
  • 3
    Why shouldn't it output 520000? After all, 025 and 000025 are the same number.
    – user253751
    Mar 30, 2015 at 7:47
  • What is "an integer with zero"? I use positive integers for counting the number of sheep in my field. I know what 25 sheep look like, but what would 025 sheep look like? Mar 30, 2015 at 7:53
  • 1
    @Sutanu: I think you should leave here your original wording with integer - thus your question will remain useful for future readers with the same initial understanding. Please read my answer below, follow the link to Oracle tutorial and implement the solution on your own - thus you will fulfil the intention of StackOVerflow. Mar 30, 2015 at 8:14

1 Answer 1

1

You are mixing types. "025" is not a number, it's a String. In a number you simply cannot distinguish between 25, 025, 0025, 00025, ... Implement your assignment as a String operation.

public String reverseString(String s) {
    // put your code here
}

You may find very useful the Oracle tutorial on Strings here: https://docs.oracle.com/javase/tutorial/java/data/strings.html

10
  • This is almost a good answer IMO; but you need to deal with a negative sign.
    – Bathsheba
    Mar 30, 2015 at 8:06
  • @Bathsheba: my answer does not prevent dealing with negative sign - it is the part //put your code here where it may be implemented :) However, until it is defined in the specification I would not be sure what the expected output should be. Should "-025" convert to "-520", "520-" or is such an input not to be expected at all? :) Mar 30, 2015 at 8:10
  • The Apache Commons StringUtils class has a reverse method. Mar 30, 2015 at 11:01
  • No. An important part of professional computer programming is knowing when to write your own method, and when to use one that somebody else has already written and tested. This is a clear case of the latter. Mar 30, 2015 at 11:10
  • Well, in 20 years of programming, I've seen loads and loads of programmers write methods for themselves that they shouldn't have. I really believe that "don't re-invent the wheel" should be one of the first lessons that every programmer should learn. What you're doing here is specifically instructing the OP to re-invent his own wheels, and the opposite lesson is what's needed here. Mar 30, 2015 at 18:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.