GetIntBinaryString is a custom function that i found on the net that converts an integer into it's binary string equivalent.
public string GetIntBinaryString(int n)
{
char[] b = new char[32];
int pos = 31;
int i = 0;
while (i < 32)
{
if ((n & (1 << i)) != 0)
{
b[pos] = '1';
}
else
{
b[pos] = '0';
}
pos--;
i++;
}
return new string(b);
}
Here is the core logic developed by me :
int cn = 0;
int sn = 0;
string si = String.Empty;
string sit = String.Empty;
ArrayList ar = new ArrayList();
sit = GetIntBinaryString(127);
for (int k = 0; k < sit.Length; k++)
{
sn += int.Parse(sit[k].ToString());
}
for (int i = 0; i < 999; i++)
{
try
{
si = GetIntBinaryString(i);
for (int k = 0; k < si.Length; k++)
{
cn += int.Parse(si[k].ToString());
}
if (cn == 7)
{
ar.Add(i);
}
cn = 0;
}
catch
{
}
}
MessageBox.Show(FindMax(ar).ToString());
What the core logic does is it isolates those numbers that contain as many 1's in it's binary represenation as does 127 (the number to check), which is 7, and then using the FindMax custom function (the logic is not included), it finds the largest in the arraylist which contains all the 3 (0-999) digit numbers which meet the said criteria.
FindMax is a custom iterative function.
Comments