简体   繁体   中英

How to get the middle 5 digits of a number

I'm doing a little project and I essentially need to figure out the middle 5 digits of a number (eg 123454321 would return 34543 ). If the number is 4 digits (eg 1234 ) it will return the middle two (in the case of 1234 this would be 23 ). If the number is 3 digits, it will return the middle number (eg 123 would return 2 ), and if the number is 1 or 2 digits the code won't accept the input.

I've tried doing some research about this online, but haven't really managed to find anything other than the "Middle-square method" but the implementation for python they have doesn't seem to work.

num = 730945296 #Random number for testing

num_len = len(str(num))
print(num*num) #debug 
print(str(num*num).zfill(num_len)) #debug
num = int(str(num*num).zfill(num_len)[round(num_len/4):round((num_len/4)*3)])


print(num)

is my representation of the implementation for python but as I stated above, this doesn't seem to work.

In this case the output was 9452 but I expected 09452 .

I'm aware I'm not doing extra checks like whether output is more than 5 digits or how long input is but I figured I should concentrate on getting the middle digits first.

Hint: The reason you are not getting 0 at the beginning of the answer, is that you are storing the value as int . Try using string as a number and the problem will be a piece of cake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM