Last active
October 7, 2015 12:48
-
-
Save roneygomes/a0ac9afbbe5ae44cc771 to your computer and use it in GitHub Desktop.
Convert a number from base ten to base minus two using two different approaches.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace NegativeBinary | |
{ | |
internal class Solution | |
{ | |
public static void Main(string[] args) | |
{ | |
for (var i = 0; i <= 10; i++) | |
{ | |
var schroeppel = string.Join(", ", toNegativeBinary_Schroeppel(i).Select(x => x.ToString())); | |
var iterativeLoop = string.Join(", ", toNegativeBinary(i).Select(x => x.ToString())); | |
Console.WriteLine("Schroepel: " + i + " => " + schroeppel); | |
Console.WriteLine("Iterative Loop: " + i + " => " + iterativeLoop); | |
Console.WriteLine(); | |
} | |
Console.WriteLine("Press any key to leave."); | |
Console.ReadKey(); | |
} | |
private static int[] toNegativeBinary_Schroeppel(int number) | |
{ | |
const uint schroeppel = 0xAAAAAAAA; | |
var result = ((number + schroeppel) ^ schroeppel); | |
var bits = new BitArray(new [] {(byte) result}); | |
return bits.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray(); | |
} | |
private static int[] toNegativeBinary(int number) | |
{ | |
var bits = new List<int>(); | |
if (number == 0) | |
{ | |
return new[] {0}; | |
} | |
while (number != 0) | |
{ | |
var remainder = number % -2; | |
number /= -2; | |
if (remainder < 0) | |
{ | |
number += 1; | |
remainder += 2; | |
} | |
bits.Add(remainder); | |
} | |
return bits.ToArray(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment