Nadesłany przez Tomasz Lubiński, 23 listopada 2006 01:00
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.Pobierz pełne rozwiązanie.
Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
Systemy.java:
//
// Konwersja z i na system dziesietny
//
// www.algorytm.org
// (c)2006 by Tomasz Lubinski
//
public class Systemy {
private static final int MAX_BASE = 36;
private static final String pattern = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// returns converted n or null if an error occurs
public static String convertTo(int n, int base)
{
String result = "";
//base is too big or too small
if ((base > MAX_BASE) || (base < 2))
return null;
//n is equal to 0, do not process, return "0"
if (n == 0)
return "0";
//process until n > 0
while (n>0)
{
result = pattern.charAt(n % base) + result;
n /= base;
}
return result;
}
// return value of x or -1 if an error occurs
private static int valueOf(char x, int base)
{
for (int i=0; i<base; i++)
{
if (x == pattern.charAt(i))
{
return i;
}
}
return -1;
}
// returns converted n or 0 if an error occurs
public static int convertFrom(String n, int base)
{
int i, x;
int p = 1;
int result = 0;
//base is too big or too small
if ((base > MAX_BASE) || (base < 2))
return 0;
n = n.toUpperCase();
for (i=n.length()-1; i>=0; i--)
{
x = valueOf(n.charAt(i), base);
if (x < 0)
{
return 0;
}
result += (x * p);
p *= base;
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("3568 w systemie dwojkowym = " + convertTo(3568, 2));
System.out.println("3568 w systemie trojkowym = " + convertTo(3568, 3));
System.out.println("3568 w systemie osemkowym = " + convertTo(3568, 8));
System.out.println("3568 w systemie szesnastkowym = " + convertTo(3568, 16));
System.out.println("3568 w systemie dwudziestkowym = " + convertTo(3568, 20));
System.out.println("100010010 w systemie dwojkowym to " + convertFrom("100010010", 2) + " w systemie dziesietnym");
System.out.println("7542 w systemie ósemkowym to " + convertFrom("7542", 8) + " w systemie dziesietnym");
System.out.println("E854 w systemie szesnastkowym to " + convertFrom("E854", 16) + " w systemie dziesietnym");
}
}

