Leetcode / 136. Single Number
Pick a programming language:
Here is the source code for the solution to this problem.
int singleNumber(int* nums, int numsSize) {
int n = 0;
for (int i = 0; i < numsSize; i++) {
n ^= nums[i];
}
return n;
}
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n = 0;
for (int i = 0; i < nums.size(); i++) {
n ^= nums[i];
}
return n;
}
};
class Solution {
public int singleNumber(int[] nums) {
int n = 0;
for (int i = 0; i < nums.length; i++) {
// a XOR a = 0
// a XOR 0 = a
// Commutative, Associative properties allow rearranging the terms.
// So in the end duplicate numbers cancel out, leaving only the single number.
n ^= nums[i];
}
return n;
}
}
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function singleNumber($nums) {
$n = 0;
foreach($nums as $num) {
$n ^= $num;
}
return $n;
}
}
class Solution:
def singleNumber(self, nums: List[int]) -> int:
n = 0
for num in nums:
n ^= num
return n
# @param {Integer[]} nums
# @return {Integer}
def single_number(nums)
n = 0
nums.each do |num|
n ^= num
end
return n
end
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
let mut n = 0;
for num in nums {
n ^= num;
}
return n;
}
}
class Solution {
func singleNumber(_ nums: [Int]) -> Int {
var n = 0
for num in nums {
n ^= num
}
return n
}
}
Did you like the lesson? 😆👍
Consider a donation to support our work: