PHP Challenges: Find the single element appears once in an array where every element appears twice except for one
Write a PHP program to find the single element appears once in an array where every element appears twice except for one.
Input : array(5, 3, 0, 3, 0, 5, 7, 7, 9)
Sample Solution :
PHP Code :
Explanation:
Here is a brief explanation of the above PHP code:
- Function definition:
- The code defines a function named "single_number()" which finds the single number in an array using a bitwise XOR operation. It takes an array '$arr' as input.
- Inside the function:
- It initializes the variable '$result' to 0.
- It iterates through the array using a "for" loop.
- Within each iteration, it performs a bitwise XOR operation between '$result' and the current element of the array.
- After iterating through the array, the variable '$result' holds the single number as a result of XORing all the elements.
- Function Call & Testing:
- An array '$num' is defined as a set of numbers.
- The "single_number()" function is called with this array as input.
- The single number found is printed using "print_r()".
Sample Output:
9
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to find a single element in an array where every element appears three times except for one.
Next: Write a PHP program to add the digits of a positive integer repeatedly until the result has a single digit.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics