即使一个数可以被2整除,也被称为奇数;如果一个数不能被2整除,则被称为奇数。给定一个数字,我们需要检查它在PHP中是奇数还是偶数。
null
例如:
Input : 42 Output : Even Explanation: The number 42 is divisible by 2 Input : 39 Output : Odd Explanation: The number 39 is not divisible by 2
我们可以通过以下两种不同的方式解决此问题:
- 使用模(%)运算符 :这是检查偶数和奇数的最简单方法,在这种方法中,我们只需使用模“%”运算符检查数字是否可被2整除。
以下程序解释了上述方法:
PHP
<?php
// PHP code to check whether the number
// is Even or Odd in Normal way
function
check(
$number
){
if
(
$number
% 2 == 0){
echo
"Even"
;
}
else
{
echo
"Odd"
;
}
}
// Driver Code
$number
= 39;
check(
$number
)
?>
输出:
Odd
时间复杂性 :O(1)
- 递归方法 :在递归方法中,我们在每次递归调用中将数字减少2。如果最后的数字是0,那么它是偶数,否则它是1,结果将是奇数。 以下是上述方法的实施情况:
PHP
<?php
// Recursive function to check whether
// the number is Even or Odd
function
check(
$number
){
if
(
$number
== 0)
return
1;
else
if
(
$number
== 1)
return
0;
else
if
(
$number
<0)
return
check(-
$number
);
else
return
check(
$number
-2);
}
// Driver Code
$number
= 39;
if
(check(
$number
))
echo
"Even"
;
else
echo
"Odd"
;
?>
输出:
Odd
时间复杂性 :O(n)
- 使用位操作: 在这个方法中,我们将用1来计算数字的位和。如果按位AND为1,则数字为奇数,否则为偶数。
下面是上述想法的实现。
PHP
<?php
// PHP code to check whether the number
// is Even or Odd using Bitwise Operator
function
check(
$number
)
{
// One
$one
= 1;
// Bitwise AND
$bitwiseAnd
=
$number
&
$one
;
if
(
$bitwiseAnd
== 1)
{
echo
"Odd"
;
}
else
{
echo
"Even"
;
}
}
// Driver Code
$number
= 39;
check(
$number
)
?>
输出:
Odd
时间复杂性: O(1)
PHP是一种专门为web开发设计的服务器端脚本语言。通过以下步骤,您可以从头开始学习PHP PHP的教程 和 PHP示例 .
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END