The program is written here to convert a hexadecimal number into its equivalent decimal number. For example, if a hexadecimal number is
Now, the equivalent decimal number will be calculated by multiplying each digit of the hexadecimal number with the increasing power of 16 (the power will starts from 0 and will increase from right to left).
Therefore, the equivalent decimal number:
2× + A×
= 2× + 10×
= 32 + 10
=
INPUT: A hexadecimal number
OUTPUT: Equivalent decimal number
PROCESS:
Step 1: [Taking the input]
Read ‘hex’ [a variable in which hexadecimal number is stored]
Step 2: [Converting into decimal number]
Set d<-0
Set b<-1
Set n<-length of the string stored in variable ‘hex’
For i=0 to n-1 repeat
If hex[i]≥'a' and hex[i]≤'z'
Set hex[i]<-hex[i]-32
[End of ‘if’]
[End of ‘for’ loop]
[Converting hexadecimal number to decimal]
For i=n-1 to 0 step -1 repeat
[if the value is a numeric digit]
If hex[i]≥'0' and hex[i]≤'9' then
Set d<-d+(hex[i]-48)×b
Set b<-b×16
[End of ‘if’]
[If the value is greater equals to 10 and less equals to 15]
else if hex[i]≥'A' and hex[i]≤'F' then
Set d<-d+(hex[i]-55)×b
Set b<-b×16
[End of ‘if’]
[End of ‘for’ loop]
[Printing the decimal value]
Print "The decimal value is: d"
Step 3: Stop.
for(i=n-1;i>=0;i--)----------------------------------------O(n)
{
//if the value is a numeric digit
if(hex[i]>='0' && hex[i]<='9')-------------O(1)
{
d=d+(hex[i]-48)*b;
b=b*16;
}
//if the value is greater equals to 10 and
//less equals to 15
else if(hex[i]>='A' && hex[i]<='F')-------O(1)
{
d=d+(hex[i]-55)*b;
b=b*16;
}
}
//printing the decimal value
printf("The decimal value is: %d",d);
}
The time complexity is O(n) where ‘n’ is the number of digits of the hexadecimal number
The space complexity is O(1) as it requires a constant number of memory spaces to execute the program for any given input.