Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if number is a multiple of 7 or contains the number 7

Tags:

java

I read a book about challenges in Java, and it gives the next question:

create a function, which get a number as argument, and detect if number is a multiple of 7 or contains the number 7.

The signature is: public boolean find7(int num)

I create this function, when the number is between 0 to 99, by the next condition:

if (num mod 7 == 0 || num / 10 ==7 || num mod 10 == 7)
   return true;

But what with number which is greater than 99? like 177, or 709? How can I detect it?

like image 959
Or Smith Avatar asked Dec 09 '25 09:12

Or Smith


2 Answers

It's probably best to leave strings out of this:

public static boolean check(final int n) {
    int m = Math.abs(n);
    while (m > 0) {
        if (m % 10 == 7)
            return true;

        m /= 10;
    }

    return n % 7 == 0;
}

The while-loop checks each digit and tests if it is 7; if it is, we return true and if it isn't, we continue. We reach the final return statement only if none of the digits were 7, at which point we return whether the number is a multiple of 7.

like image 138
arshajii Avatar answered Dec 11 '25 23:12

arshajii


if (num % 7 ==0 || ("" + num).contains("7") ){
    return true;
}
like image 22
Alexandros Avatar answered Dec 11 '25 23:12

Alexandros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!