Skip to content

Instantly share code, notes, and snippets.

@suryansh011
Created September 24, 2024 13:06
Show Gist options
  • Save suryansh011/72821d57ce670594cc8b5cceb77e351c to your computer and use it in GitHub Desktop.
Save suryansh011/72821d57ce670594cc8b5cceb77e351c to your computer and use it in GitHub Desktop.
Convert Decimal to any representation of the base 2 to base 16.
import java.util.Scanner;
public class Kary {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
long i = Integer.parseInt(scan.nextLine());
int k = Integer.parseInt(scan.nextLine());
if(k < 2 || k > 16) return;
long n = i;
int power = 1;
while(power <= n / k) power *= k;
while(power > 0) {
if(n < power) { System.out.print(0); }
else {
char c = 'x';
switch ((int) n / power) {
case 1: c = '1'; break;
case 2: c = '2'; break;
case 3: c = '3'; break;
case 4: c = '4'; break;
case 5: c = '5'; break;
case 6: c = '6'; break;
case 7: c = '7'; break;
case 8: c = '8'; break;
case 9: c = '9'; break;
case 10: c = 'A'; break;
case 11: c = 'B'; break;
case 12: c = 'C'; break;
case 13: c = 'D'; break;
case 14: c = 'E'; break;
case 15: c = 'F'; break;
}
System.out.print(c);
n -= power * (n / power);
}
power /= k;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment