Finding the Addition of Value from numbers of array
Now I want to get the numbers for which the given variable days is the sum of any digits in the array.
For example
80 = 64+16 (if I/p is 80, O/P should be 64,16)
37 = 32 + 4 + 1 (If I/P is 37, O/P should be 32 , 4 , 1 )
Console.WriteLine("Enter Input:");
string input = Console.ReadLine();
double days = Convert.ToDouble(input);
//short days = 80;
short[] possibleDays = new short[] { 1, 2, 4, 8, 16, 32, 64 };
short sum = 0;
string totalValues = string.Empty;
for (int i = possibleDays.Length; i >= 1; i--)
{
sum += possibleDays[i - 1];
if (sum == days)
{
totalValues += possibleDays[i - 1] + ";";
break;
}
else
{
if (sum > days)
{
sum -= possibleDays[i - 1];
}
else
{
totalValues += possibleDays[i - 1] + "'";
}
}
}
totalValues = totalValues.TrimEnd(',');
Console.WriteLine(totalValues);
Console.ReadKey();
For example
80 = 64+16 (if I/p is 80, O/P should be 64,16)
37 = 32 + 4 + 1 (If I/P is 37, O/P should be 32 , 4 , 1 )
Console.WriteLine("Enter Input:");
string input = Console.ReadLine();
double days = Convert.ToDouble(input);
//short days = 80;
short[] possibleDays = new short[] { 1, 2, 4, 8, 16, 32, 64 };
short sum = 0;
string totalValues = string.Empty;
for (int i = possibleDays.Length; i >= 1; i--)
{
sum += possibleDays[i - 1];
if (sum == days)
{
totalValues += possibleDays[i - 1] + ";";
break;
}
else
{
if (sum > days)
{
sum -= possibleDays[i - 1];
}
else
{
totalValues += possibleDays[i - 1] + "'";
}
}
}
totalValues = totalValues.TrimEnd(',');
Console.WriteLine(totalValues);
Console.ReadKey();
Comments
Post a Comment