Skip to content

Commit c92a104

Browse files
committed
Add Reverse Bits, Single Number, Happy Number C#
1 parent 9f88e08 commit c92a104

File tree

3 files changed

+105
-0
lines changed

3 files changed

+105
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class Solution {
2+
//XOR solution
3+
public int SingleNumber(int[] nums) {
4+
var result = 0;
5+
for(int i=0; i<nums.Length; i++){
6+
result ^= nums[i];
7+
}
8+
return result;
9+
}
10+
11+
//Dictionary solution
12+
public int SingleNumber(int[] nums) {
13+
var dict = new Dictionary<int, int>();
14+
for(int i=0; i<nums.Length; i++){
15+
if(!dict.ContainsKey(nums[i])){
16+
dict.Add(nums[i], 1);
17+
}else{
18+
dict[nums[i]]++;
19+
}
20+
}
21+
return dict.First(x => x.Value == 1).Key;
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class Solution
2+
{
3+
public bool IsHappy(int n)
4+
{
5+
var hs = new HashSet<int>();
6+
var left = 0;
7+
//HashSet is the key
8+
while (hs.Add(n))
9+
{
10+
var sum = 0;
11+
while (n > 0)
12+
{
13+
left = n % 10;
14+
sum += left * left;
15+
n /= 10;
16+
}
17+
18+
if (sum == 1)
19+
{
20+
return true;
21+
}
22+
else
23+
{
24+
n = sum;
25+
}
26+
}
27+
return false;
28+
}
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
public class Solution
2+
{
3+
4+
//Bitwise solution
5+
public uint reverseBits(uint n) {
6+
if(n == 0) return 0;
7+
uint result = 0;
8+
for(int i=0; i<32; i++){
9+
result <<= 1;
10+
if((n & 1) == 1) result++;
11+
n >>= 1;
12+
}
13+
return result;
14+
}
15+
16+
17+
//Stack solution
18+
public uint reverseBits(uint n)
19+
{
20+
//Push to stack
21+
var stack = new Stack<uint>();
22+
while (n > 0)
23+
{
24+
stack.Push(n % 2);
25+
n = n / 2;
26+
}
27+
28+
//Fill empty slots
29+
var length = stack.Count;
30+
if (length < 32)
31+
{
32+
var tl = 32 - length;
33+
for (int i = 0; i < tl; i++)
34+
{
35+
stack.Push(0);
36+
}
37+
}
38+
39+
//Construct number
40+
uint b = 1;
41+
uint result = 0;
42+
if (stack.Pop() == 0) result = 0;
43+
else result = 1;
44+
while (stack.Count > 0)
45+
{
46+
b *= 2;
47+
var r = stack.Pop();
48+
result = result + b * r;
49+
}
50+
51+
return result;
52+
}
53+
}

0 commit comments

Comments
 (0)