-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnyBaseToAnyBase.java
46 lines (35 loc) · 1.23 KB
/
AnyBaseToAnyBase.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package numberssystem;
import java.util.Scanner;
public class AnyBaseToAnyBase {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int inputBase = scanner.nextInt();
int outputBase = scanner.nextInt();
int toDecimal = convertAnyBaseToDecimal(number, inputBase);
int result = convertDecimalToBaseB(toDecimal, outputBase);
System.out.println(result);
}
private static int convertAnyBaseToDecimal(int number, int inputBase) {
int result = 0;
int power = 1;
while (number > 0) {
int remainder = number % 10;
result += remainder * power;
power = power * inputBase;
number = number / 10;
}
return result;
}
private static int convertDecimalToBaseB(int number, int base) {
int convertedNumber = 0;
int multiplicationFactor = 1;
while (number > 0) {
int remainder = number % base;
convertedNumber += remainder * multiplicationFactor;
multiplicationFactor = multiplicationFactor * 10;
number = number / base;
}
return convertedNumber;
}
}