尝试确定我的整数列表是由奇数还是偶数组成,我想要的输出是真和/或假的列表。我可以在列表lst上执行以下操作,还是需要创建循环? A是输出。
List <int> lst = new List <int>();
A = IsOdd(lst);
答案 0 :(得分:46)
只需使用模数
遍历列表并在每个项目上运行以下内容
if(num % 2 == 0)
{
//is even
}
else
{
//is odd
}
或者,如果你想知道是否所有都是偶数,你可以做这样的事情:
bool allAreEven = lst.All(x => x % 2 == 0);
答案 1 :(得分:39)
您可以尝试使用Linq投影列表:
var output = lst.Select(x => x % 2 == 0).ToList();
这将返回一个新的bool列表,{1, 2, 3, 4, 5}
将映射到{false, true, false, true, false}
。
答案 2 :(得分:19)
至少有7种不同的方法来测试数字是奇数还是偶数。但是,如果你read through these benchmarks,你会发现上面提到的TGH,模数运算是最快的:
if (x % 2 == 0)
//even number
else
//odd number
以下是一些其他方法(来自website):
//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
答案 3 :(得分:1)
#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();
}
}
答案 4 :(得分:0)
- 简单代码 -
#endregion #region奇数/偶数按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