比如有数字  2,4,8,16,32,64 ...2+8+32=42   我如何使用net程序把42拆分成 2,8,32这里可能是任何数字相加 ,, 不过数字都是以倍数产生的。比如 
2+4+8+16=30
32+8=40
4+16+32=52请写详细代码 , 谢谢此题分 100

解决方案 »

  1.   

    List<int> list=new List<int>();
    int i=1;
    while(i<30)
    {
      i=i<<1;
      if(i^30<30)
       {
         list.Add(i);
       }
    }
      

  2.   


        protected void Page_Load(object sender, EventArgs e)
        {
            //这个数是你要输入的
            int test = 40;
            int num = 0;
            int i = 0;
            while (test > 0)
            {
                if (num <= test)
                {
                    num = (int)Math.Pow(2, i);
                }
                else
                {
                    int tmp = (int)Math.Pow(2, i - 2);
                    Response.Write(tmp);
                    Response.Write("<br/>");
                    test = test - tmp;
                    i = 0;
                    num = 0;
                }
                i++;
            }
        }
    //思路可以这样,自己优化下,不难的。
      

  3.   

    用数学运算:List<int> Separate(int n)
    {
    List<int> result = new List<int>();
    while ( n> 0)
    {
    int m = (int)Math.Pow(2, (int)Math.Floor(Math.Log(n, 2)));
    result.Add(m);
    n -= m;
    }
    return result;
    }
    或者直接:List<int> Separate(int n)
    {
    List<int> result = new List<int>();
    int m = 1;
    while (m <= n)
    {
    m <<= 1; //也就是 m=m*2
    }
    while (n > 0)
    {
    if (m <= n)
    {
    result.Add(m);
    n -= m;
    }
    m >>= 1; //也就是 m=m/2
    }
    return result;
    }
      

  4.   


    using System;
    using System.Linq;
    using System.Collections;
    using System.Collections.Generic;class Program
    {
    static void Main() {
    int input = 0;
    input = int.Parse(Console.ReadLine());
    var s = string.Join("+", devide(input));
    Console.WriteLine("{0}={1}", s, input);
    Console.ReadLine();
        }

    static List<int> bits = Enumerable.Range(0,31).Select(i => 1 << i).ToList();
    static List<int> devide(int x)
    {
    int[] tmp = new int[] {x};
    BitArray ba = new BitArray(tmp);

    return ba.OfType<bool>().Select((v,i) => new { value = v, index = i}).Where(t => t.value == true).Select(t => bits[t.index]).ToList();
    }
    }
      

  5.   

    没时间了,写下思路:
    设相加后的数为A
      2,4,8,16,32,64 ... 为B
    C=A
    则当循环A<=B次数
    C/B[0] % 2,如果余数为0,则无B[0],反则有B[0]
    如果有B[0],则C-=B[0]
    CONTINUE
      

  6.   

    public static void main(String[] args) {    int n = 1231234;
        
        for (int p = 1; n > 0; n >>= 1, p <<= 1) {
            if ((n & 1) == 1) {
                System.out.println(p);
            }
        }
    }当然了 n 不能小于 1
      

  7.   

    不防参考这个:
    http://www.cnblogs.com/insus/archive/2012/07/08/2581134.html
      

  8.   

    应该还包括2^0=1吧,不然奇数就拆不了。
    int v = 55;
    int r = 1;
    while (v > 0)
    {
    if ((v & 1) == 1)
    Response.Write(r + " ");
    v = v >> 1;
    r = r << 1;
    }
    1 2 4 16 32