---
title: "Single Number find"  
description: "Single Number find"  
author: "Steilla Mitchel"  
published: 2024-06-12  
updated: 2024-06-12  
canonical: https://www.mindstick.com/forum/160727/single-number-find  
category: "c#"  
tags: ["c#", "programming language", "programming help", "programs"]  
reading_time: 2 minutes  

---

# Single Number find

Given a **non-empty** [array of integers](https://www.mindstick.com/forum/157932/write-a-program-to-find-the-missing-number-in-an-array-of-integers) `nums`, every element appears *twice* [except](https://www.mindstick.com/blog/144/union-intersection-and-except-operator-in-sql-server) for one. Find that single one.

You [must](https://www.mindstick.com/articles/12978/top-reasons-why-every-magento-ecommerce-store-must-opt-for-mobile-app) implement a solution with a linear [runtime](https://www.mindstick.com/articles/52/creating-timer-at-runtime-in-c-sharp-dot-net) complexity and use only [constant](https://www.mindstick.com/forum/34714/difference-between-statics-vs-constant-in-c-sharp) [extra](https://www.mindstick.com/blog/63570/5-ways-to-make-money-with-the-extra-space-in-your-home) space.

## Replies

### Reply by Ravi Vishwakarma

Let's write code to find a single number from the [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net), we use the [**XOR**](https://en.wikipedia.org/wiki/Bitwise_operations_in_C) technique to solve this problem in C#.

```cs
public static int SingleNumber(int[] nums)
{
    // Initialize result to 0. This will hold the unique number.
    int result = 0;

    // Loop through each number in the array
    foreach (int num in nums)
    {
        // XOR the current number with the result
        // This will cancel out numbers that appear twice and leave the unique number
        result ^= num;
    }

    // Return the unique number found
    return result;
}
```

If I take the array [2, 2, 1].

### Step-by-Step Execution

**Initialization**:

- **Initial State**: `result = 0`
- We start with `result` initialized to `0`.

**First Iteration** (`num = 2`):

- **Operation**: `result ^= 2` which means `result = result ^ 2`
- **Calculation**: `0 ^ 2 = 2` (since `0 XOR anything` equals `that thing`)
- **State after iteration**: `result = 2`

**Second Iteration** (`num = 2`):

- **Operation**: `result ^= 2` which means `result = result ^ 2`
- **Calculation**: `2 ^ 2 = 0` (since `a XOR a = 0`)
- **State after iteration**: `result = 0`

**Third Iteration** (`num = 1`):

- **Operation**: `result ^= 1` which means `result = result ^ 1`
- **Calculation**: `0 ^ 1 = 1` (since `0 XOR anything` equals `that thing`)
- **State after iteration**: `result = 1`

## Final Result

`return result;`

- **Return Value**: `1`


---

Original Source: https://www.mindstick.com/forum/160727/single-number-find

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
