-
Notifications
You must be signed in to change notification settings - Fork 3
/
anybasesubtraction.java
53 lines (39 loc) · 1.08 KB
/
anybasesubtraction.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
47
48
49
50
51
52
53
import java.util.*;
public class anybasesubtraction{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int b = scn.nextInt();
int n1 = scn.nextInt();
int n2 = scn.nextInt();
int d = getSubtraction(b, n1, n2);
System.out.println(d);
}
public static int getSubtraction(int b, int n1, int n2){
int dec1 = anybasetodecimal(n1,b);
int dec2 = anybasetodecimal(n2,b);
int sum = dec2 - dec1;
int rsum = decimaltoanybase(sum,b);
return rsum;
}
public static int anybasetodecimal(int n, int b){
int rv = 0;
int p = 1;
while(n > 0){
int dig = (n%10);
n /= 10;
rv += dig * p;
p = p * b;
}
return rv;
}
public static int decimaltoanybase(int n, int b){
int dn = 0;
for(int i = 1;n > 0;){
int dig = (n % b);
n = n / b;
dn += dig * i;
i = i * 10;
}
return dn;
}
}