You know number bases have place values that start at 1 (base to the 0 power) and proceed right-to-left to base^1, base^2, and so on. In base -2, the place values are 1, -2, 4, -8, 16, -32, ... (reading from right to left). Thus, counting from 1 goes like this: 1, 110, 111, 100, 101, 11010, 11011, 11000, 11001, and so on.
Eerily, negative numbers are also represented with 1's and 0's but no sign. Consider counting from -1 downward: 11, 10, 1101, 1100, 1111, and so on.
Please help the cows convert ordinary decimal integers (range -2,000,000,000 .. 2,000,000,000) to their counterpart representation in base -2.
Input
A single integer to be converted to base -2
Output
A single integer with no leading zeroes that is the input integer converted to base -2. The value 0 is expressed as 0, with exactly one 0.
Example
Input:
-13
Output:
110111
https://www.spoj.pl/problems/NEG2/
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TheMoronicCowmpouter
{
public static void main( String args[] ) throws Exception
{
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
int numero = Integer.parseInt( br.readLine() );
boolean redondeoAbajo = true;
int prueba = numero;
if( numero < 0 )
{
prueba = -prueba;
redondeoAbajo = false;
}
//Buffer temporal donde almacenaremos la salida
char[] salida = new char[ 35 ];
int tamanio = 35;
if( numero == 0 )
System.out.println( "0" );
else
{
/*
* Nos basamos en el algoritmo presentado en
* http://en.wikipedia.org/wiki/Negative_base, realizamos
* una ligera modificacion para que solo tengamos que
* trabajar con numeros enteros positivos.
*
* La modificacion consiste en ir redondeando alternadamente
* hacia arriba y hacia abajo, luego de realizar cada division.
*/
while( prueba > 0 )
{
// Verificamos si el numero actual es par
if( ( prueba & 1 ) == 0 )
salida[ -- tamanio ] = '0';
else
salida[ -- tamanio ] = '1';
if( redondeoAbajo )
prueba = prueba >> 1;
else
prueba = ( prueba + 1 ) >> 1;
redondeoAbajo = !redondeoAbajo;
}
System.out.println( new String( salida, tamanio, 35 - tamanio ) );
}
}
}
No hay comentarios:
Publicar un comentario