Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int[] numbers = { 1, 1, 1, -1, -1 };
- int coefficientCombinations = (int) Math.Pow(2, numbers.Length) - 1;
- for (int coefficients = coefficientCombinations; coefficients > 0; coefficients--)
- {
- if(onlyOneBitSet(coefficients))
- {
- continue;
- }
- int sum = 0;
- for (int index = 0; index < numbers.Length; index++)
- {
- int bitIndex = (numbers.Length - 1) - index;
- int numberIndex = index;
- int coefficient = getBit(coefficients, bitIndex);
- sum += coefficient * numbers[numberIndex];
- }
- if (sum == 0)
- {
- //Print the Sum
- }
- }
- static int getBit(int coefficients, int bitIndex)
- {
- return (coefficients >> bitIndex) & 1;
- }
- static bool onlyOneBitSet(int coefficients)
- {
- int setBitCount = 0;
- int highestBit = 31;
- for(int i = 0; i <= highestBit; i++)
- {
- if(((coefficients >> i) & 1) == 1)
- {
- setBitCount++;
- }
- }
- if(setBitCount == 1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement