# [algorgithm][leetcode]007 - Reverse Integer ###### tags: `algorhithm`,`leetcode` 題目說明: >https://leetcode.com/problems/reverse-integer/ >Reverse digits of an integer. >#Example1: x = 123, return 321 >#Example2: x = -123, return -321 > *python程式碼來源: > https://play.google.com/store/apps/details?id=com.machinelearningforsmallbusiness.leetcodepython&hl=en_US > 其餘版本皆改寫自此app的程式碼 ### python ```python= # From Leetcode Python android app # https://leetcode.com/problems/reverse-integer/ # Reverse digits of an integer. # Example1: x = 123, return 321 # Example2: x = -123, return -321 # Repeatedly multiply previous result by 10 and add last digit. # Time - O(n) where n is the number of digits. # Space - O(n), same number of digits in output as input. def reverse(x): """ :type x: int :rtype: int """ negative = x < 0 # record if negative and change to positive x = abs(x) reversed = 0 while x != 0: reversed = reversed * 10 + x % 10 x //= 10 if reversed > 2**31 - 1: # required to pass leetcode test cases, not applicable for python return 0 return reversed if not negative else -reversed print(reverse(-123)) #-321 ``` ### javascript ```javascript= function reverse(n){ is_negative= n < 0 ? true:false n = Math.abs(n) result=0 while(n!=0){ result = result * 10 + n % 10 n = Math.floor(n/10) } // required to pass leetcode test cases if(result > Math.pow(2,31)-1 ){ return 0 } return is_negative? -result : result } print(reverse(-123)) ``` ### Ruby ```ruby= def reverse(n) is_negative=false is_negative = n < 0 ? true : false n=(n).abs #取絕對值 result=0 while n!=0 result = result*10 + n % 10 #ruby語言特性,整數互除可直接取得商數 n =n / 10 end # required to pass leetcode test cases if result > 2**32-1 return 0 end if is_negative return -result else return result end end p reverse(-123) ```