DEV Community

dev.to staff
dev.to staff

Posted on

9 4

Daily Challenge #292 - ISBN-10 Identifiers

ISBN-10 identifiers are ten digits. The first nine digits are on the range 0 to 9. The last digit can be either on the range 0 to 9 or the letter 'X' used to indicate a value of 10.

For an ISBN-10 to be valid, the sum of the digits multiplied by their position has to equal zero modulo 11. For example, the ISBN-10: 1112223339 is valid because:
(((1*1)+(1*2)+(1*3)+(2*4)+(2*5)+(2*6)+(3*7)+(3*8)+(3*9)+(9*10)) % 11) == 0

Create the function validISBN10() to return true if and only if the input is a valid ISBN-10 Identifier.

Examples

validISBN10('1293000000'), true
validISBN10('048665088X'), true
validISBN10('1234512345'), false
validISBN10('1293') , false

Tests

validISBN10('1112223339')
validISBN10('X123456788')
validISBN10('1234512345')

Good luck!


This challenge comes from nklein on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (3)

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS) • Edited
const validISBN10 = (num) => { 
  if (!/[0-9]{9}[X0-9]{1}/.test(num)) return false;
  return (num.split('').map((d, i) => d === 'X' ? (10 * (i + 1)) : (d * (i + 1))).reduce((a, b) => a + b) % 11 === 0)
}
Collapse
 
vuchuru27916 profile image
Preethi Vuchuru27916 • Edited
public static boolean validISBN10(String s){
        int sum = 0;
        if(s.matches("[0-9]{9}[X0-9]{1}"))
        {
            for(int i = 0; i < s.length(); i++) {
                sum += s.charAt(i) == 'X' ? 10 * (i + 1) : Character.getNumericValue(s.charAt(i)) * (i + 1);
            }
            if(sum % 11 == 0) return true;
        }
        return false;
    }
Collapse
 
peter279k profile image
peter279k

Here is the simple solution with JavaScript and using for loop to resolve this challenge :).

function validISBN10(isbn) {
  let index = 0;
  let checkSum = 0;
  let xCount = 0;
  for (; index < isbn.length; index++) {
    if (isbn[index] === 'X') {
      xCount += 1;
    }
    checkSum += parseInt(isbn[index]) * (index+1);
  }

  if (isbn.length !== 10) {
    return false;
  }

  if (isbn[isbn.length-1] === 'X' && xCount === 1) {
    return true;
  }

  return checkSum % 11 === 0;
}

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay