1 Star 0 Fork 0

蔡茂昌 / Algorithms-implemented-in-Java

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
AnyBaseToDecimal.java 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
Varun Upadhyay 提交于 2017-06-28 11:01 . Created AnyBaseToDecimal.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
// Driver program
public class AnyBaseToDecimal {
public static void main (String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inp = br.readLine();
int base = Integer.parseInt(br.readLine());
System.out.println("Input in base " + base + " is: " + inp);
System.out.println("Decimal value of " + inp + " is: " + convertToDecimal(inp, base));
br.close();
}
/**
* This method produces a decimal value of any given input number of any base
* @param inp_num String of which we need the decimal value and base in integer format
* @return string format of the decimal value
*/
public static String convertToDecimal(String inp_num, int base) {
int len = inp_num.length();
int num = 0;
int pow = 1;
for (int i=len-1; i>=0; i--) {
if (valOfChar(inp_num.charAt(i)) >= base) {
return "Invalid Number";
}
num += valOfChar(inp_num.charAt(i))*pow;
pow *= base;
}
return String.valueOf(num);
}
/**
* This method produces integer value of the input character and returns it
* @param c Char of which we need the integer value of
* @return integer value of input char
*/
public static int valOfChar(char c) {
if (c >= '0' && c <= '9') {
return (int)c - '0';
}
else {
return (int)c - 'A' + 10;
}
}
}
Java
1
https://gitee.com/edmondcmc/Algorithms-implemented-in-Java.git
git@gitee.com:edmondcmc/Algorithms-implemented-in-Java.git
edmondcmc
Algorithms-implemented-in-Java
Algorithms-implemented-in-Java
master

搜索帮助