本文主要是介绍Write a C program to find the parity of an unsigned integer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
reference:
http://www.geeksforgeeks.org/write-a-c-program-to-find-the-parity-of-an-unsigned-integer/
Problem Definition:
Parity: Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it contains even number of 1-bits.
Solution:
1. Initialize parity = 0
2. Loop while n != 0 a. Invert parity parity = !parityb. Unset rightmost set bitn = n & (n-1)
3. return parity
Code:
/* Function to get parity of number n. It returns 1if n has odd parity, and returns 0 if n has evenparity */
bool getParity(unsigned int n)
{bool parity = 0;while (n){parity = !parity;n = n & (n - 1);} return parity;
}
这篇关于Write a C program to find the parity of an unsigned integer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!