Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi.

Here I have an array

C#
short days = 80;
short[] possibleDays = new short[] { 1, 2, 4, 8, 16, 32, 64 };


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 ).

Can you please help me writing a logic to my scenario.

Thanks.
Posted

Your array is an array of binary power:
2^0=1, 2^1=2, 2^2=4, 2^3=8, 2^4=16, 2^5=32, 2^6=64

Simply check corresponding bits states:
C++
for (i=1; i<=64; i<<=1)
  if (day & i)
    printf(%d ", i);
 
Share this answer
 
v4
Comments
CPallini 21-May-15 3:51am    
5.Please note:
i<<1
shoud be instead
i<<=1

Frankie-C 21-May-15 3:53am    
Grazie Carlo
CPallini 21-May-15 10:41am    
:-)
you can Try this It's Working.....

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();
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900