Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Validate a barcode [duplicate]

A barcode of EAN-13 symbology consists of 13 digits (0-9). The last digit of this barcode is its check digit. It is calculated by the following means (the barcode 8923642469559 is used as an example):

  1. Starting from the second digit, sum up all alternating digits and multiply the sum by 3:

    8 9 2 3 6 4 2 4 6 9 5 5 9
     | | | | | |
     9 +たす 3 +たす 4 +たす 4 +たす 9 +たす 5 = 34
     |
     34 ×ばつ 3 = 102
    
  2. Then, sum up all of the remaining digits, but do not include the last digit:

    8 9 2 3 6 4 2 4 6 9 5 5 9
    | | | | | |
    8 +たす 2 +たす 6 +たす 2 +たす 6 +たす 5 = 29
    
  3. Add the numbers obtained in steps 1 and 2 together:

    29 + 102 = 131
    
  4. The number you should add to the result of step 3 to get to the next multiple of 10 (140 in this case) is the check digit.

If the check digit of the barcode matches the one calculated as explained earlier, the barcode is valid.


More examples:

6537263729385 is valid. 1902956847427 is valid. 9346735877246 is invalid. The check digit should be 3, not 6.


Your goal is to write a program that will:

  1. Receive a barcode as its input.
  2. Check whether the barcode is valid
  3. Return 1 (or equivalent) if the barcode is valid, 0 (or equivalent) otherwise.

This is , so the shortest code in terms of bytes wins.

Answer*

Draft saved
Draft discarded
Cancel

AltStyle によって変換されたページ (->オリジナル) /