5次检查的倍数

Utk*_*tav 2 c c++ algorithm

这段代码如何适用于5的倍数

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;
}
Run Code Online (Sandbox Code Playgroud)

ami*_*mit 8

它首先使n2分裂.

接下来,它通过0.1再次乘以来检查它是否可以除以10 10.如果它可以被分割的想法10,你将回到原始的,只有这样.

因此,如果修改n可以被10除除 - 它当然也可以除以5,并且由于修改n总是可以除以2,如果它可以除以5则可以除以10,并且算法可以工作.

注意:这是非常未提及的,特别是由于浮点精度问题,可能会因大值而中断.%应优先使用运营商:return (n % 5) == 0


Joe*_*Joe 5

这是代码如何使用一些示例.

if ( (n&1) == 1 ) //Checks if the number is odd
    n <<= 1; //Multiplies the number by 2 if odd

x = ( (int)(x * 0.1) //Divides the number 10 then truncates any decimal places
    * 10 ) //Multiplies it back by 10

if ( (int)x == n ) //If the floating point value equals the (semi) original value its divisible by 5
        return true;

return false; //Other wise false
Run Code Online (Sandbox Code Playgroud)

例:

15 & 1 == 1 //15 is odd
15 <<= 1; //n is now 30

30 / 10 = 3;
3 * 10 = 30; //x is now 30

30 == 30 //15 is a multiple of 5
Run Code Online (Sandbox Code Playgroud)
17 & 1 == 1 //17 is odd
17 <<= 1; //n is now 34

34 / 10 = 3.4;
((int)3.4 = 3) * 10 = 30; //x is now 30

30 != 34 //17 is not a multiple of 5.
Run Code Online (Sandbox Code Playgroud)

正如其他人所说,只是简单地使用mod运算符%.