This is the given code. I am accessing each element of the string and trying to multiply it with powers of 8 but, the result is coming out to be wrong.
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
int od(string s)
{
reverse(s.begin(),s.end());
int ans=0;
for(int i=0;i<s.length();i )
{
ans=ans s[i]*pow(8,i);
}
return ans;
}
int main()
{
string s;
cin>>s;
cout<<od(s);
return 0;
}
CodePudding user response:
The problem lies in the line:
ans=ans s[i]*pow(8,i);
Here s[i] is a character. When numerical operations are performed with it, its ASCII value is taken. So here's an easy fix:
ans=ans ((s[i]-'0'))*pow(8,i);
This will give you the correct answers for obvious reasons.
CodePudding user response:
This code is the issue
ans=ans s[i]*pow(8,i);
string characters (chars) are ASCII, so "0" in ASCII is actually 48. ASCII mappings are here https://en.cppreference.com/w/cpp/language/ascii
I suppose you could check each character and map it to the decimal value, or you could use something like std::stoi
std::stoi(myoctalstring, nullptr, 8);
https://en.cppreference.com/w/cpp/string/basic_string/stol
CodePudding user response:
There are two issues: the string's elements are digits, not numbers ('0'
is not the same thing as 0
), and pow
is a floating-point operation, which you should not use in conjunction with integers.
You can get the number that corresponds to a digit by subtracting '0'
from it, and you can keep track of the current power of eight as you loop.
int od(string s)
{
reverse(s.begin(), s.end());
int ans = 0;
int power = 1;
for(int i = 0; i < s.length(); i )
{
ans = ans (s[i] - '0') * power;
power *= 8;
}
return ans;
}
but it's actually simpler to not reverse the string and multiply the temporary result on each step instead:
int od(string s)
{
int ans = 0;
for(int i = 0; i < s.length(); i )
{
ans = ans * 8 s[i] - '0';
}
return ans;
}
CodePudding user response:
You need to use atoi
or _ttoi
, something like atoi(s[i])
.