An efficient way to write this code snippet? [closed]

巧了我就是萌 提交于 2019-12-23 18:34:56

问题


Ways of rewriting this code more efficiently and/or shortly to save bytes and appear less verbose?

if(N % 2 == 0 && (N == 6 || N == 8 || N == 10 || N == 12 || N == 14 || N== 16 || N == 18 || N == 20 ))
{
    printf("Weird\n");
}

Given the language is C, although doesn't matter if its java or php or any other language :-).


回答1:


Supposing that N has an unsigned integral type, and you are more interested minimal source code than in clarity, then you might write

if (((N - 6) & 14) + 6 == N) {
    printf("Weird\n");
}

Explanation:

The first operation, N - 6, shifts the range of the acceptable values from 6 - 20 to 0 - 14. The latter range can be expressed with four bits.

The second operation, & 14, is a bitwise and with bit pattern 1110. That will leave even numbers in the range 0 - 14 unchanged, but it will convert odd numbers to even and it will clear any higher bits. The only values that survive unchanged are the ones derived from the original target values in the first step.

The third operation reverses the first, so that the result can be compared directly with the original number. If the combined sequence of operations reproduces the original number, then that number is one of the ones you were looking for.




回答2:


Why won't you just do :

if (N % 2 == 0 && (N >= 6 && N <= 20))
{
     /* ... */
}



回答3:


Given N is unsigned integer.

if(N % 2 == 0 && (N-6) <= 14)
{
    printf("Weird\n");
}


来源:https://stackoverflow.com/questions/36959554/an-efficient-way-to-write-this-code-snippet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!