-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuestion10.java
More file actions
86 lines (69 loc) · 1.63 KB
/
Question10.java
File metadata and controls
86 lines (69 loc) · 1.63 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.*;
public class Question10 {
static int val(char c) {
if (c >= '0' && c <= '9')
return (int) c - '0';
else
return (int) c - 'A' + 10;
}
static int toDeci(String str, int base) {
int len = str.length();
int power = 1;
int num = 0;
for (int i = len - 1; i >= 0; i--) {
if (val(str.charAt(i)) >= base) {
System.out.printf("Invalid Number");
return -1;
}
num += val(str.charAt(i)) * power;
power = power * base;
}
return num;
}
static char reVal(int num) {
if (num >= 0 && num <= 9)
return (char) (num + '0');
else
return (char) (num - 10 + 'A');
}
static String fromDeci(int base, int inputNum) {
String res = "";
while (inputNum > 0) {
res += reVal(inputNum % base);
inputNum /= base;
}
res = reverse(res);
return res;
}
static void convertBase(String s, int a, int b) {
int num = toDeci(s, a);
String ans = fromDeci(b, num);
System.out.print(ans);
}
static String reverse(String input) {
char[] a = input.toCharArray();
int l, r = a.length - 1;
for (l = 0; l < r; l++, r--) {
char temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return String.valueOf(a);
}
// Driver Code
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
String s = sc.next();
System.out.print("Enter base1: ");
int a = sc.nextInt();
System.out.print("Enter base2: ");
int b = sc.nextInt();
convertBase(s, a, b);
sc.close();
}
}
/*Satyam Sekhar Barik
* Regd-no : 2141002032
* sec : CSE-U
* */