测试整数列表是奇数还是偶数
本文关键字:整数 测试 列表 | 更新日期: 2023-09-27 18:31:21
试图确定我的整数列表是由奇数还是偶数组成的,我想要的输出是真/假的列表。 我可以在列表上执行以下操作还是需要创建一个循环?A 是输出。
List <int> lst = new List <int>();
A = IsOdd(lst);
您可以尝试使用 Linq 投影列表:
var output = lst.Select(x => x % 2 == 0).ToList();
这将返回一个新的布尔值列表,以便{1, 2, 3, 4, 5}
映射到{false, true, false, true, false}
。
只需使用模数
遍历列表并对每个项目运行以下命令
if(num % 2 == 0)
{
//is even
}
else
{
//is odd
}
或者,如果你想知道是否都是,你可以做这样的事情:
bool allAreEven = lst.All(x => x % 2 == 0);
至少有 7 种不同的方法可以测试一个数字是奇数还是偶数。但是,如果你通读这些基准,你会发现正如上面提到的TGH,模运算是最快的:
if (x % 2 == 0)
//even number
else
//odd number
以下是其他一些方法(来自网站):
//bitwise operation
if ((x & 1) == 0)
//even number
else
//odd number
//bit shifting
if (((x >> 1) << 1) == x)
//even number
else
//odd number
//using native library
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
//even number
else
//odd number
#region even and odd numbers
for (int x = 0; x <= 50; x = x + 2)
{
int y = 1;
y = y + x;
if (y < 50)
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{" + y + "} order by Asc");
Console.ReadKey();
}
else
{
Console.WriteLine("Odd number is #{" + x + "} : even number is #{0} order by Asc");
Console.ReadKey();
}
}
//order by desc
for (int z = 50; z >= 0; z = z - 2)
{
int w = z;
w = w - 1;
if (w > 0)
{
Console.WriteLine("odd number is {" + z + "} : even number is {" + w + "} order by desc");
Console.ReadKey();
}
else
{
Console.WriteLine("odd number is {" + z + "} : even number is {0} order by desc");
Console.ReadKey();
}
}
--简单代码--
#region odd / even numbers order by desc
//declaration of integer
int TotalCount = 50;
int loop;
Console.WriteLine("'n---------Odd Numbers -------'n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 == 0)
{
Console.WriteLine("Even numbers : #{0}", loop);
}
}
Console.WriteLine("'n---------Even Numbers -------'n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 != 0)
{
Console.WriteLine("odd numbers : #{0}", loop);
}
}
Console.ReadLine();
#endregion