I am getting Wrong Output for converting hexadecimal to decimal numbwe

  c++

If I put input 1CF i am getting output 207 not 463 which is actual number. Is there anything I am doing wrong so it is not printing correct output.

#include <bits/stdc++.h>
using namespace std;

int hexadecimalTodecimal(string n){
    int ans = 0;
    int x = 1;
    int s = n.size();

    for(int i = s-1; i>0; i--)
    {
        if(n[i] >= '0' && n[i] <= '9')
        {
            ans += x*(n[i] - '0');
        }
        else if(n[i] >= 'A' && n[i] <='F')
        {
            ans += x*(n[i] - 'A' + 10);
        }
        x *= 16;
    }
    return ans;
}

int main(){
    string n;
    cin>>n;
    
    cout<<hexadecimalTodecimal(n)<<endl;
}

Source: Windows Questions C++

LEAVE A COMMENT