-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortIntegersByBits.cs
More file actions
63 lines (52 loc) · 1.39 KB
/
SortIntegersByBits.cs
File metadata and controls
63 lines (52 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Text;
namespace CodeForecs
{
class ArrayObject : IComparable<ArrayObject>
{
public int NoOfBinaryDigits { get; set; }
public int Value { get; set; }
public ArrayObject(int digits, int value)
{
NoOfBinaryDigits = digits;
Value = value;
}
public int CompareTo(ArrayObject other)
{
if (other == null)
return -1;
if (NoOfBinaryDigits == other.NoOfBinaryDigits)
return Value.CompareTo(other.Value);
return NoOfBinaryDigits.CompareTo(other.NoOfBinaryDigits);
}
}
class SortIntegersByBits
{
public int SetBits(int n)
{
int count = 0;
while (n > 0)
{
n &= (n - 1);
count++;
}
return count;
}
public int[] SortByBits(int[] arr)
{
List<ArrayObject> lst = new List<ArrayObject>();
foreach(int i in arr)
{
lst.Add(new ArrayObject(SetBits(i), i));
}
lst.Sort();
int[] answer = new int[arr.Length];
for(int i = 0; i < answer.Length; i++)
{
answer[i] = lst[i].Value;
}
return answer;
}
}
}