Skip to the content

Is the ISBN valid?

Problem

Every book has an ISBN printed on the back: ten characters that say which book it is. The last one is not information, it is a check digit: it is there to catch it when somebody typed the other nine wrong.

Write a function that takes that code as text and returns true if the ISBN is valid and false if it is not.

Here is the check: multiply the first character by 10, the second one by 9, the third one by 8, and so on until the last one, which goes by 1. If the whole sum divides evenly by 11, the code is valid. With "3-598-21508-8" the sum is 264, and 264 divided by 11 is 24 with nothing left over.

The rules: dashes do not count, wherever they show up, so take them out or skip them. Without them exactly ten characters must be left, not one more and not one less. The first nine are digits. The last one can be a digit or an "X", which is worth 10 there; anywhere else an X is not valid.

Any other letter makes the code invalid, wherever it shows up: you cannot skip it and you cannot count it as 0.

Examples

  • A good ISBN

    "3-598-21508-8" → true

  • The check digit does not add up

    "3-598-21508-9" → false

  • Ends with an X

    "3-598-21507-X" → true

  • No dashes

    "3598215088" → true

  • An X in the middle

    "3-598-2X507-9" → false

  • Another letter at the end

    "4-598-21507-B" → false

  • One digit too many

    "3-598-21508-96" → false

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def is_valid_isbn(text):
    pass

JavaScript

function isValidIsbn(text) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n) challenges

See all challenges →