Sorry if that sound like stupid, I'm just a newbie to programming
At first I thought it was easy and started writing code and I find myself with bunch of errors.
Then I came up with this:
number = 12345 reverse = str(number)[::-1] print(reverse)
It's just cheating you can say, I converted integer into string and made that string reverse.
After a while I thought, I'm just stupid to code like this but then later I googled and I found this solution which is more complicated to understand:
number = 12345 reverse = 0 while number > 0: last_digit = number % 10 reverse = reverse * 10 + last_digit number = number // 10 print(reverse)
Can anyone please explain what's going on here?
Without converting the number to a string:
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
Which runs like:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
Then pass the result to reverse:
>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
This makes it much easier to test each part of the code separately and see what's going on when you put it all together.
Is there a more efficient way to reverse an int
Reversing a number
Leetcode Reverse Integer Question
Please read this guide on how to format your code in your post. I'd be more than happy to help once it's formatted in a way that makes it easier to read.
https://www.reddit.com/r/javahelp/wiki/code_guides
More on reddit.com