This is Discussion thread about Playing with number system
Discussion About Playing with number system
What is the problem in my code its not giving desired output
import java.util.;
public class Main {
public static int anyBaseToAnyBase(int sb , int db , int snum) {
// converting a no of source base to decimal base
int decimalno=0;
int multiplier = 1;
int ans=0;
while(snum!=0) {
int rem = snum%sb;
decimalno = decimalno+(remmultiplier);
multiplier = multiplier*10;
snum = snum/sb;
}
//System.out.println(“Decimal no:”+decimalno);
// converting a no from decimal base to source base
while(decimalno!=0) {
int rem1 = decimalno%db;
ans = ans+(rem1*multiplier);
multiplier=multiplier*10;
decimalno=decimalno/db;
}
return ans;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int sb = sc.nextInt();
int db = sc.nextInt();
int snum = sc.nextInt();
int res = anyBaseToAnyBase(sb, db, snum);
System.out.println(res);
}
}
First covert given number from source base to decimal , then convert converted decimal number to destination base.
int val(char c){
if(c>=‘0’ and c<=‘9’){
return c-‘0’;
}
else{
return c-‘A’+10;
}
}
char value(int np){
if(np>=0 and np<=9){
return np+‘0’;
}
else{
return np+‘A’-10;
}
}
void revp(char*str){
int f=strlen(str);
for(int i=0;i<f/2;i++){
char temp=str[i];
str[i]=str[f-i-1];
str[f-i-1]=temp;
}
}
int convert(char *a,int b){
int f=strlen(a);
int num=0;
int power=1;
for(int i=f-1;i>=0;i–){
if(val(a[i])>=16){
return -1;
}
num+=val(a[i])power;
power=powerb;
}
return num;
}
char*convert1(int numb,int u){
static char ar[100];
int i=0;
while(numb!=0){
ar[i++]=value(numb%u);
numb=numb/u;
}
ar[i]=’\0’;
revp(ar);
return ar;
}
int main() {
int no;
cin>>no;
int k;
cin>>k;
cin.get();
char a[100];
cin.getline(a,100,'\n');
int n=convert(a,no);
cout<<convert1(n,k);
}
#include
#include<math.h>
using namespace std;
long long int convert(int s,int d,long long int n){
long long int decimal=0;
int power=0;
while(n>0){
decimal+=(n%10)*(pow(s,power));
n=n/10;
power++;
}
long int mul=1;
long long int converted=0;
while(decimal>0){
converted+=mul*(decimal%d);
decimal=decimal/d;
mul=mul*10;
}
long long int result=0;
int mul2=1;
while(converted>0){
result+=mul2*(converted%10);
converted=converted/10;
mul2=mul2*10;
}
return result;
}
int main() {
int s,d;
long long int n;
cin>>s>>d>>n;
cout<<convert(s,d,n)<<endl;
return 0;
}