查找数组数的逻辑 [英] A logic in finding the numbers of array

查看:176
本文介绍了查找数组数的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.

这里有一个数组

Hi.

Here I have an array

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



现在,我要获取给定变量days是数组中任何数字的总和的数字.
例如
80 = 64 + 16(如果I/p为80,则O/P应该为64,16)
37 = 32 + 4 +1(如果I/P为37,则O/P应为32,4,1).

您能帮我写一个符合我情况的逻辑吗?

谢谢.



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.

推荐答案

您可以尝试使用它....

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();


您的数组是二进制幂的数组:
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:

for (i=1; i<=64; i<<=1)
  if (day & i)
    printf(%d ", i);


这篇关于查找数组数的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆