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 subtract n1 from n2 and print the value.
A base bOutput Format
A number n1
A number n2
A number of base b equal in value to n2 - n1.
Constraints
2 <= b <= 10
0 <= n1 <= 256
n1 <= n2 <= 256
Sample Input
8
1
100
Sample Output
77
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 = getDifference(b, n1, n2);
System.out.println(d);
}
public static int getDifference(int b, int n1, int n2){
// write your code here
if(n1<n2){
int temp = n1;
n1=n2;
n2=temp;
}
int borrow = 0, res = 0,p=1;
while(n1 > 0 || n2 > 0 || borrow != 0){
int d1 = n1%10;
n1/=10;
d1 += borrow;
borrow = 0;
int d2 = n2%10;
n2/=10;
if(d1<d2){
d1+=b;
borrow = -1;
}
res += (d1-d2)*p;
p*=10;
}
return res;
}
}
Comments
Post a Comment