如何检查整数的所有数字是否均匀?
实施例
$a = 22444648;
$b = 324687;
$a
的所有数字均为:2%2 == 0,4%2 == 0 ...所以我想返回true。另一方面,$b
应该返回false,因为3%2!= 0。
答案 0 :(得分:2)
您可以使用str_split($integer)
将整数拆分为数字数组。然后,您可以遍历数组元素,并在遇到不均匀的数字时立即返回false。
function isEven($integer){
$digits = str_split($integer);
foreach($digits as $digit){
if($digit % 2 != 0) return false;
}
return true;
}
答案 1 :(得分:0)
这个问题有很多可能的解决方案 - 如果您正在寻找单行,您可以使用preg_match()
检查整数是否包含所有偶数值。
如果模式与给定主题匹配,则preg_match()返回1,否则返回0;如果发生错误,则返回FALSE。
如果所有值均为偶数,则Host workid
HostName bitbucket.org
IdentityFile ~/.ssh/workid
Host personalid
HostName bitbucket.org
IdentityFile ~/.ssh/personalid
的正则表达式应返回/^[02468]+$/
,否则1
(或0
)。然后,它只是将结果转换为false
的情况;即:
boolean
我建议根据您的具体使用情况对此进行测试。例如,您是否必须支持负数?或者,填充数字是否可以接受;例如:$a = 224455;
$hasAllEvens = (boolean) preg_match('/^[02468]+$/', $a);
甚至是0024
?
由于有许多可能的解决方案,您可以享受其他选择。这是一个更为复杂的例子:
00000
收率:
<?php
// split the integer into an array and
// apply a reduce function over each element.
//
// this function applies a bitwise AND where
// the left-hand value is 1, and the right-hand
// value is a single digit integer. an operation
// with an even number returns `0` and an operation
// with an odd number returns `1`. this result is
// added to the `carry` value, which is the result
// of the previously applied function.
//
// once iteration is complete, the resulting value
// is `0` is all integers were even, and a value
// greater than `0` representing a "count" of any
// odd values encountered.
//
// finally we negate this value to cast to
// a boolean to get our final result.
function hasAllEvens($int)
{
return !array_reduce(str_split($int), function ($carry, $item) {
return (1 & $item) + $carry;
});
}
// and a quick test...
// any number that has at least one
// odd integer will return false.
foreach (range(0, 21) as $int) {
$result = hasAllEvens($int) ? 'yes' : 'no';
printf("hasAllEvens(%d) -> %s\n", $int, $result);
}
等等。
希望这会有所帮助:)