Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def nice_number(n):
- # Local program state to help us determine what to check while looping through each digit
- # In a nice number, you begin by counting up continuously (or not at all)
- # Then at some point we begin counting down continuously (or not at all)
- countUp = true
- # Convert n to a string to make array accesses easier/cleaner, as str[i] accesses the ith char in the string
- nStr = str(n)
- #Array accesses are to n[x] and n[x+1]. This range prevents out-of-range accesses.
- for x in range(0, len(n) - 2):
- if countUp = true:
- #Number counts up at current digit
- if int(nStr[x+1]) == int(nStr[x]) + 1:
- continue
- #Number counts down at current digit
- else if int(nStr[x+1]) == int(nStr[x]) - 1:
- countUp = false
- continue
- #If this digit doesn't count up nor down, then n is not Nice.
- else:
- return false
- else:
- #Since countUp == false, we only have to check if current digit counts down.
- if int(nStr[x+1]) == int(nStr[x]) - 1:
- continue
- #If this digit doesn't count down, then n is not Nice.
- else:
- return false
- #We made it through the whole loop, therefore n is Nice.
- return true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement