Write a program to convert a hexadecimal number to a decimal number.
Example 1:
Input:5F
Output:95
Example 2:
Input:4AB
Output:1195
Approach
Java
public class HexadecimalToDecimal {public static void main(String[] args) {String hexa = "4AB";int decimal = hexaToDecimal(hexa);System.out.println("Decimal is " + decimal);}private static int hexaToDecimal(String hexa) {int n = hexa.length();int decimal = 0;for (int i = 0; i < n; i++) {if (Character.isDigit(hexa.charAt(i))) {int num = Integer.parseInt(String.valueOf(hexa.charAt(i)));decimal += Math.pow(16, n - i - 1) * num;} else {int num = (int) hexa.charAt(i) - 55;decimal += Math.pow(16, n - i - 1) * num;}}return decimal;}}
C++
#include <bits/stdc++.h>using namespace std;//function to convert from hexadecimal to//decimalint hexadecimalToDecimal(string hexadecimal){int decimal=0;int n=hexadecimal.size();for(int i=0;i<n;i++){//if hexadecimal[i]>='0'&&hexadecimal[i]<='9'if(hexadecimal[i]>='0'&&hexadecimal[i]<='9'){int num=hexadecimal[i]-'0';decimal=decimal+pow(16,n-i-1)*num;}//if hexadecimal[i]>='A'&&hexadecimal[i]<='F'else{int num=hexadecimal[i]-'A'+10;decimal=decimal+pow(16,n-1-i)*num;}}return decimal;}int main(){string hexadecimal="5F";int decimal=hexadecimalToDecimal(hexadecimal);cout<<"Decimal is ";cout<<decimal<<"\n";return 0;}
No comments:
Post a Comment