Recent Posts

Tuesday 30 June 2015

Converting Numbers to Different Numerical Systems in JAVA

You may have to change the numbers from one format to other format, as like from decimal to hexagon . Here i have tried the different approach where you can convert from one numerical system to other numerical system using the digits in that numerical system.

For Example , if i want to convert the 10 from decimal to hexagon. I will provide the input in the following format along with the number of Test Cases.
1
# input1: 10 0123456789 0123456789abcdef
# output: a

Here is the logic for that written in JAVA language.

import java.lang.*; import java.util.*; public class Numbers{ @ SuppressWarnings ("deprication") public static void main(String[] args) { String result=""; Scanner sc=new Scanner(System.in); int i=0,tests=Integer.parseInt(sc.next()); while(i++<tests){ String numbr=sc.next(); String source_pattern=sc.next(); String target_pattern=sc.next(); Number_System source=new Number_System(source_pattern); Number_System target=new Number_System(target_pattern); result=result+"Case #"+i+": "+target.genValue(source.genDeciValue(numbr))+"\n"; } System.out.print(result); } } class Number_System{ int len=0; String pattern; public Number_System(String seq){ len=seq.length(); pattern=seq; } public int genDeciValue(String x){ int i=0,v,str_len=x.length(); Double value=new Double(0.0); while(i<str_len){ v=pattern.indexOf(x.charAt(str_len-i-1)); value=v*Math.pow(len,i)+value; i++; } return value.intValue(); } public String genValue(int x){ String res=""; while(x!=0) { if(x<len){ res=pattern.charAt(x)+""+res; break; } res=pattern.charAt(x%len)+""+res; x=x/len; } return res; } }

Smart Siva

Author & Editor

In Life every second is important, In programming every line of code is important.

0 comments:

Post a Comment

 
biz.