snk
snk

Reputation: 91

How to find out if a specific digit is in the middle of an integer value?

Homework question is asking me to write a program that would output True if an integer is odd and has the number "0" in the middle of it. I figured out how to get it to print True if a number is odd but can't figure out how to detect if the number 0 is in the middle.

I've figured out the first condition which would be detecting if it's odd.

input:
  def is_cyclops(n):
    if len(str (n)) % 2 != 0:
      return True
    return False
  print (is_cyclops(11011))
output:
True

I want to know how to get the code to detect the number 0 in the middle.

Upvotes: 0

Views: 533

Answers (2)

Vishwam Pandya
Vishwam Pandya

Reputation: 29

This code will work for an input n.

n = str(n)
if(len(n)%2==0): #Checks if even
    if(n[len(n)/2]==0): #Checks for presence of 0
        return True
else:
    if(n[len(n+1)/2]==0): #Checks for presence of 0
        return True

Upvotes: 0

ChrisFNZ
ChrisFNZ

Reputation: 617

I'll provide a response in the form of an algorithm:

  • Convert the number to a string
  • Detect whether the string has an even or odd number of characters (because even numbered strings don't have a single "middle" character)
  • Look at the middle character which is character # (len(str)/2)-0.5
  • That's your middle character

Upvotes: 3

Related Questions