一种有效的方式来写这个code段? [英] An efficient way to write this code snippet?

查看:101
本文介绍了一种有效的方式来写这个code段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更有效和/或短改写这个code,以节省字节,显得不那么详细?的方式

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");
}

鉴于语言

是C,但不要紧,如果它的Java或PHP或任何其他语言:-)。

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

推荐答案

假设 N 有一个无符号整型,你更感兴趣的最小源$ C ​​$ C较清晰,那么你可能会写

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");
}

说明

第一个操作, N - 6 ,从 6 转移可接受值的范围 - 20 0 - 14 。后者范围可以是具有四个比特pssed前$ P $

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.

第二个操作,&安培; 14 ,是一个位的的有位模式 1110 。这将范围 0 甚至把号码 - 14 不变,但它会转换奇数,甚至,它会清除任何高位。该生存不变的值只有从原来的目标值在第一步骤中得到的那些。

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.

这篇关于一种有效的方式来写这个code段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆