Multiple Realization Schemes of python Inversion of a Three bit Integer
- 2021-09-24 23:04:26
- OfStack
When practicing this problem on LintCode, look up the data and find a variety of methods, which are summarized as follows.
输入 | 输出 |
---|---|
123 | 321 |
Type 1: Realization of remainder rounding by integer method
class Solution:
"""
@param number: A 3-digit number.
@return: Reversed number.
"""
def reverseInteger(self, number):
g = number%10 # Take out single digits
s = (int(number/10))%10 # Take out 10 Number of digits
b = int(number/100) # Take out hundreds of digits
return g*100+s*10+b
if __name__ == "__main__":
so = Solution()
print (so.reverseInteger(123))
python does not automatically intercept reserved integers like C language 1, which needs to be converted by int 1
Type 2: Use string slicing
def reverseInteger(self, number):
number=str(number)
result=number[::-1]
result=(int(result))
return result
How to Deal with String by Borrowing
Type 3: Using the stack
def reverseInteger(self, number):
number=str(number)# Analog stacking
l=list(number)
result=""
while len(l)>0:
result+=l.pop()# Analog stack
return int(result)
Supplement: Python program: Any input of a 3-digit, and then the 3-digit position inverted output.
Method 1
The input of three hundreds of digits, 10 digits and individual digits are represented in turn, and then the individual digits are exchanged with the hundred digits.
# Input number = 123, Output 321
number = int(input(' Please enter 1 A 3 Number of digits: '))
a = number%10 # Individual position
b = number//10%10 #10 Bit
c = number//100 # Hundred digits
re_number = a*100 + b*10 + c
print('%d The inversion number of is :%d'%(number,re_number)) # No. 1 1 Species of output mode
print('{0} The inversion number of is :{1}'.format(number,re_number)) # No. 1 2 Species of output mode
Method 2
The input of 3 digits in the form of a string with list () method list, and then reverse sequence from the list of bits, 10 bits, 100 bits, the output attention to the str type conversion to int type.
# Input number = 123, Output 321
number = input(' Please enter 1 A 3 Number of digits: ')
list1 = list(number) # The that will be entered 3 The string of digits is stored in the list
list1.reverse() # Invert list elements
a = int(list1[0]) # Take out the elements of the inverted list and change their types to int Type
b = int(list1[1])
c = int(list1[2]) # You can also reverse the elements in the list without reversing it
re_number = a*100 + b*10 + c
print('%s The inversion number of is :%s'%(number,re_number))
print('%d The inversion number of is :%d'%(int(number),re_number))