Base-2 in Java


The problem

On this problem you need to convert integers numbers from and to a negative-base binary system.

Destructive-base techniques can accommodate all the identical numbers as normal place-value techniques, however each constructive and damaging numbers are represented with out using a minus signal (or, in laptop illustration, an indication bit); this benefit is countered by an elevated complexity of arithmetic operations.

To assist perceive, the primary eight digits (in decimal) of the Base(-2) system is:

[1, -2, 4, -8, 16, -32, 64, -128]

Instance conversions:

Decimal, negabinary

6,   '11010'
-6,  '1110'
4,   '100'
18,  '10110'
-11, '110101'

The answer in Java code

Choice 1:

public class Resolution {
    
    public static String intToNegabinary(int i) {
        return Integer.toBinaryString((i+0xAAAAAAAA)^0xAAAAAAAA);
    }
    
    public static int negabinaryToInt(String s) {
        return s.chars().map(i->i-'0').scale back(0,(a,v)->v-2*a);
    }
    
}

Choice 2:

public class Resolution {

    public static String intToNegabinary(int i) {
        var sb = new StringBuilder();

        whereas (i != 0) {
            int the rest = Math.abs(i) % 2;
            sb.append(the rest);
            if (i < 0 && the rest > 0) i--;
            i /= -2;
        }
        var outcome = sb.reverse().toString();
        return outcome.isEmpty() ? "0" : outcome;
    }

    public static int negabinaryToInt(String s) {
        var strReversed = new StringBuilder(s).reverse();
        int outcome = 0;

        for (int i = 0; i < strReversed.size(); i++)
            if (strReversed.charAt(i) == '1')
                outcome += Math.pow(-2, i);

        return outcome;
    }
}

Choice 3:

public class Resolution {

  public static String intToNegabinary(int i) {
    return Integer.toUnsignedString(toNegabinary(i), 2);
  }

  public static int negabinaryToInt(String s) {
    return fromNegabinary(Integer.parseUnsignedInt(s, 2));
  }

  public static int toNegabinary(int i) {
    return (i + NEGATIVE_DIGITS) ^ NEGATIVE_DIGITS;
  }

  public static int fromNegabinary(int i) {
    return (i ^ NEGATIVE_DIGITS) - NEGATIVE_DIGITS;
  }

  personal static remaining int NEGATIVE_DIGITS = 0xAAAAAAAA;

}

Check circumstances to validate our resolution

import org.junit.Check;
import static org.junit.Assert.assertEquals;

public class SolutionTest {
    @Check
    public void testIntToNegabinary() {
        assertEquals("11010", Resolution.intToNegabinary(6));
        assertEquals("1110", Resolution.intToNegabinary(-6));
    }
    
    @Check
    public void testNegabinaryToInt() {
        assertEquals(6, Resolution.negabinaryToInt("11010"));
        assertEquals(-6, Resolution.negabinaryToInt("1110"));
    }
    
}

Leave a Reply

Your email address will not be published. Required fields are marked *