日期:2014-05-18 浏览次数:21133 次
/// <summary> /// 利用异或来判断奇偶性 /// 先把十进制转换为二进制后再利用二进制位逐个异或来判断结果奇偶性 /// h:当h为0时,flag为true则为奇数,反之亦然 /// </summary> class Program { static void Main(string[] args) { int a,h; bool flag=false; string b; char[] c = { }; while (true) { h = 0; Console.WriteLine("请输入一个十进制数:"); try { a = Convert.ToInt32(Console.ReadLine()); } catch { Console.WriteLine("输入不正确,正常退出!"); break; } b = Convert.ToString(a, 2); c = b.ToCharArray(); for (int k = 0; k < c.Length - 1; k++) { h ^= c[k] ^ c[k + 1]; if (h == 0) { flag = false; } else { flag = true; } } if (flag) { Console.WriteLine("偶数\n"); } else { Console.WriteLine("奇数\n"); } } Console.ReadKey(); } }
b = Convert.ToString(a, 2); c = b.ToCharArray(); for (int k = 0; k < c.Length - 1; k++) { h ^= c[k] ^ c[k + 1]; } if (h != 0) { Console.WriteLine("偶数\n"); } else { Console.WriteLine("奇数\n"); }
------解决方案--------------------
while (true)
{
string s = Console.ReadLine();
int x = 0;
if (!int.TryParse(s, out x))
continue;
Console.WriteLine((x ^ (x + 1)) == 1 ? "偶数" : "奇数");
}