Given a positive number n, write a function isMultipleof5(int n) that returns true if n is multiple of 5, otherwise false. You are not allowed to use % and / operators.
Method 3 (Set last digit as 0 and use floating point trick)
A number n can be a mulpile of 5 in two cases. When last digit of n is 5 or 10. If last bit in binary equivalent of n is set (which can be the case when last digit is 5) then we multiply by 2 using n<<=1 to make sure that if the number is multpile of 5 then we have the last digit as 0. Once we do that, our work is to just check if the last digit is 0 or not, which we can do using float and integer comparison trick.
Method 1 (Repeatedly subtract 5 from n)
Method 2 (Convert to string and check the last character)
Convert n to a string and check the last character of the string. If the last character is ’5′ or ’0′ then n is multiple of 5, otherwise not.
Read full article from Check if a number is multiple of 5 without using / and % operators | GeeksforGeeks
Method 3 (Set last digit as 0 and use floating point trick)
A number n can be a mulpile of 5 in two cases. When last digit of n is 5 or 10. If last bit in binary equivalent of n is set (which can be the case when last digit is 5) then we multiply by 2 using n<<=1 to make sure that if the number is multpile of 5 then we have the last digit as 0. Once we do that, our work is to just check if the last digit is 0 or not, which we can do using float and integer comparison trick.
bool
isMultipleof5(
int
n)
{
/* If n is a multiple of 5 then we make sure that last
digit of n is 0 */
if
( (n&1) == 1 )
n <<= 1;
float
x = n;
x = ( (
int
)(x*0.1) )*10;
/* If last digit of n is 0 then n will be equal to (int)x */
if
( (
int
)x == n )
return
true
;
return
false
;
}
Method 2 (Convert to string and check the last character)
Convert n to a string and check the last character of the string. If the last character is ’5′ or ’0′ then n is multiple of 5, otherwise not.
Read full article from Check if a number is multiple of 5 without using / and % operators | GeeksforGeeks