Forsarna_
Forsarna_

Reputation: 11

How do I make this ISBN-verifier more efficient?

I am trying to make this code more efficient. How should I go about and do it?

It is a class that is called from another one in Java. I am not the best when it comes to algorithmic efficiency so I appreciate all help I can get.

Thanks in advance.

public class Algorithm {
    public static boolean check(String isbn){

        if (isbn.length() == 13) {
            return check13(isbn);
        }

        else if (isbn.length() == 10) {
            return check10(isbn);
        }

        else {
            // System.out.println("Invalid length!");
            return false;
        }
    }

    private static boolean check13(String isbn) {
        int sum = 0;
        for (int i = 0; i < isbn.length(); i++) {
            int temp_val = isbn.charAt(i);
            if (i%2 == 1) {
                temp_val *= 3;
                sum += temp_val;
            }
            else {
                sum += temp_val;
            }
        }
        // System.out.println("Valid ISBN!");
        // System.out.println("Invalid ISBN!");
        return sum % 10 == 0;
    }

    private static boolean check10(String isbn) {
        int sum = 0;
        for (int i = 10; i > isbn.length(); i--) {
            sum += isbn.charAt(i) * i;

        }
        // System.out.println("Valid ISBN!");
        // System.out.println("Invalid ISBN!");
        return sum % 11 == 0;
    }
}

Upvotes: -1

Views: 52

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102903

your algorithm takes as many steps as the ISBN is long, it's not going to be any more efficient than this.

Upvotes: 2

Related Questions