Problem:
1. You are given a base b.Input Format
2. You are given two numbers n1 and n2 of base b.
3. You are required to add the two numbes and print their value in base b.
A base bOutput Format
A number n1
A number n2
A number representing the sum of n1 and n2 in base b.
Constraints
2 <= b <= 10
0 <= n1 <= 256
0 <= n2 <= 256
Sample Input
8
777
1
Sample Output
1000
Solution:
import java.util.*;
public class Main{
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 = getSum(b, n1, n2);
System.out.println(d);
}
public static int getSum(int b, int n1, int n2){
// write ur code here
n1 = convertBase(n1,b,10);
n2 = convertBase(n2,b,10);
return convertBase(n1+n2,10,b);
}
public static int convertBase(int num,int sourceBase, int destBase){
int pow =1, newNum = 0;
while(num>0){
newNum += (num%destBase) * pow;
pow *= sourceBase;
num/= destBase;
}
return newNum;
}
}
Comments
Post a Comment