GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coding-problems/Other/reverse_integer.py at master · Pranshu-Raj/coding-problems Expand file tree/ Copy pathreverse_integer.pyMore file actions 55 lines (39 loc) · 847 Bytes / Copy pathreverse_integer.pyFile metadata and controls55 lines (39 loc) · 847 Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 ''' Reverse Integer Given signed integer, reverse digits of an integer. Input: 123 Output: 321 Input: -123 Output: -321 Input: 120 Output: 21 ========================================= Simple solution, mod 10 to find all digits. Time Complexity: O(N) , N = number of digits Space Complexity: O(1) ''' ############ # Solution # ############ def reverse_integer(x): if x == 0: return 0 sign = x // abs(x) # find the sign, -1 or 1 x *= sign # make positive x, or x = abs(x) res = 0 while x > 0: res = (res * 10) + (x % 10) x //= 10 return res * sign ########### # Testing # ########### # Test 1 # Correct result => 321 print(reverse_integer(123)) # Test 2 # Correct result => -321 print(reverse_integer(-123)) # Test 3 # Correct result => 21 print(reverse_integer(120)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |