long conversion C++ arduino - c++

I have this error, and I can't figure this out.
cannot convert 'String' to 'long int' in assignment
I want to send all RC5 codes beetween 0x00 and 0xFF by IR led and arduino.
I am using IRremote
Here is my code :
for(int i = 0;i < 16 ;i++){
value = i;
if(i == 10){
value = "a";
}
if(i == 11){
value = 'b';
}
if(i == 12){
value = 'c';
}
if(i == 13){
value = 'd';
}
if(i == 14){
value = 'e';
}
if(i == 15){
value = 'f';
}
for(int j = 0;j < 16 ;j++){
value2 = j;
if(j == 10){
value2 = "a";
}
if(j == 11){
value2 = 'b';
}
if(j == 12){
value2 = 'c';
}
if(j == 13){
value2 = 'd';
}
if(j == 14){
value2 = 'e';
}
if(j == 15){
value2 = 'f';
}
valueTotal = "0x" + value + value2;
toSend = valueTotal;
irsend.sendRC5(toSend , 12);
delay(20);
} }

Assuming you're using this library https://github.com/z3t0/Arduino-IRremote/blob/master/IRremote.h , sendRC5 takes an unsigned long argument. You either seem to have got confused because of examples using hexadecimal literals into thinking it requires a string, or need to send your string as multiple words.
Assuming the former, something like this sends all the codes:
for (int i = 0x0; i <= 0xff ; ++i) {
irsend.sendRC5(i, 12);
delay(20);
}

Related

Any C++ simple standard function to convert 32 bit signed 2's complement hexadecimal string to decimal? [duplicate]

I have to write a program that converts unsigned hex to dec and dec to hex and signed hex to dec and dec to hex, without using the stream filters "hex" and "dec". My program works for the unsigned converting of hex to dec and dec to hex but NOT for the SIGNED hex to dec and dec to hex. Any help would be greatly appreciated. Thank You in advance!
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
void convertDecToHex(unsigned hexNumber);
int convertHexToDec(char hex[], unsigned numberSize);
signed SignedDecToHex (signed DecNumberSigned);
signed SignedHexToDec (int number);
int main (){
unsigned choice, numberSize = 0, hexNumber;
signed DecNumberSigned;
char hex[100000];
string number, HexNumberSigned;
while (1){
cout << "Enter 1 to convert from unsigned Dec to Hex:" << endl << "Enter 2 to convert from unsigned Hex to Dec:"
<< endl << "Enter 3 to convert from signed Dec to Hex:"<< endl << "Enter 4 to convert from signed Hex to Dec:" << endl ;
cin >> choice;
if (choice == 1){
cout << "Enter unsigned dec # to convert to hex: " << endl;
cin >> hexNumber;
convertDecToHex( hexNumber);
}//1
if (choice == 2){
cout << "Enter unsigned hex # to convert to dec: " << endl;
cin >> number;
numberSize = number.size();
strcpy(hex, number.c_str());
cout << convertHexToDec(hex, numberSize) << endl;
}//2
if (choice == 3){
cout << "Enter signed dec to convert to hex: " << endl;
cin >> DecNumberSigned;
convertDecToHex( SignedDecToHex(DecNumberSigned));
}//3
if (choice == 4){
cout << "Enter signed hex to convert to dec: " << endl;
cin >> HexNumberSigned;
numberSize = HexNumberSigned.size();
strcpy(hex, HexNumberSigned.c_str());
cout << SignedHexToDec(convertHexToDec( hex, numberSize)) << endl;
}//4
}//while
system ("pause");
}//main
void convertDecToHex(unsigned hexNumber){
int remainder, i=0;
unsigned m[99999], total, x;
char n [99999];
i=0;
do {
remainder = hexNumber % 16;
hexNumber /= 16;
m[i] = remainder;
i++;
}//doLooop
while (hexNumber > 0);
total = i;
for (i=0, x = total - 1; i < total; i++, x--){
if (m[i] == 1) n[x] = '1';
if (m[i] == 2) n[x] = '2';
if (m[i] == 3) n[x] = '3';
if (m[i] == 4) n[x] = '4';
if (m[i] == 5) n[x] = '5';
if (m[i] == 6) n[x] = '6';
if (m[i] == 7) n[x] = '7';
if (m[i] == 8) n[x] = '8';
if (m[i] == 9) n[x] = '9';
if (m[i] == 10) n[x] = 'A';
if (m[i] == 11) n[x] = 'B';
if (m[i] == 12) n[x] = 'C';
if (m[i] == 13) n[x] = 'D';
if (m[i] == 14) n[x] = 'E';
if (m[i] == 15) n[x] = 'F';
}
for (i=0; i < total; i++)
cout << n[i];
cout << endl;
}//DecToHex
int convertHexToDec(char hex[], unsigned numberSize){
int i, j;
int n[10000];
unsigned sum = 0;
char a,b,c,d,e,f;
for (i = 0 ; i < numberSize; i++){
if (hex[i] == '1') n[i] = 1;
if (hex[i] == '2') n[i] = 2;
if (hex[i] == '3') n[i] = 3;
if (hex[i] == '4') n[i] = 4;
if (hex[i] == '5') n[i] = 5;
if (hex[i] == '6') n[i] = 6;
if (hex[i] == '7') n[i] = 7;
if (hex[i] == '8') n[i] = 8;
if (hex[i] == '9') n[i] = 9;
if (hex[i] == 'a' || hex[i] == 'A') n[i] = 10;
if (hex[i] == 'b' || hex[i] == 'B') n[i] = 11;
if (hex[i] == 'c' || hex[i] == 'C') n[i] = 12;
if (hex[i] == 'd' || hex[i] == 'D') n[i] = 13;
if (hex[i] == 'e' || hex[i] == 'E') n[i] = 14;
if (hex[i] == 'f' || hex[i] == 'F') n[i] = 15;
}//forLoop
for (i = 0, j = numberSize - 1; i < numberSize , j >= 0 ; i++, j--)
sum += pow(16,i) * n[j];
return sum;
}//HexToDec
signed SignedDecToHex (signed DecNumberSigned){
signed convertNumber;
convertNumber = DecNumberSigned + (pow (2,16));
return convertNumber;
}// SignedDecToHex
signed SignedHexToDec (int number){
int newNumber;
newNumber = number - (pow (2,16));
return newNumber;
}//SingedHexToDec
Don't use pow() when doing integer arithmetic. pow returns values as double which is inexact, and may result in the value being off by one when converting it to an int.
Theoretically doubles may be exact when working with numbers being powers of two. But that assumes that you know what you are doing, which at the moment, you don't :-)
Better use bit-shifting when possible:
pow(2,n) --> 1 << n
How to implement pow(16, n) using bitshifting is left as excercise for the reader.
Hint: ((i^n)^m) = i ^ (n*m)
I use some like this:
long int dec = strtol("0x0A01006F", NULL, 16); // return 167837807
printf("%d\n", dec);
long int hex = strtol("167837807", NULL, 10); // return A01006F
printf("%02X\n", hex);

How do I modify an input through multiple functions in C++?

Basically I have to encode a name into a Soundex Code. The helper functions I implemented do the following:
Discard all non-letter characters from the surname: dashes, spaces, apostrophes, and so on.
Encode each letter as a digit
Coalesce adjacent duplicate digits from the code (e.g. 222025 becomes 2025).
Replace the first digit of the code with the first letter of the original name, converting to uppercase.
Remove all zeros from the code.
Make the code exactly length 4 by padding with zeros or truncating the excess.
Excuse the implementation of the helper functions, I know they could be implemented better. But when I manually pass the output from one function to another I see that the result is what I want. It's only when I combine them all into one function that I see that the output I pass is as if I didn't modify the input I passed at all. I believe my issue might have to do with passing by reference but doing that for all my functions made no difference or gave an incorrect output.
#include <iostream>
#include <string>
string removeNonLetters(string s) {
string result = "";
for (int i = 0; i < s.length(); i++) {
if (isalpha(s[i])) {
result += s[i];
}
}
return result;
}
string encode(string name) {
std::transform(name.begin(), name.end(), name.begin(), ::toupper);
string encoded = "";
for (int i = 0; i < name.size(); ++i) {
if (name[i] == 'A' || name[i] == 'E' || name[i] == 'I' || name[i] == 'O' || name[i] == 'U' || name[i] == 'H' || name[i] == 'W' || name[i] == 'Y')
encoded += '0';
else if (name[i] == 'B' || name[i] == 'F' || name[i] == 'P' || name[i] == 'V')
encoded += '1';
else if (name[i] == 'C' || name[i] == 'G' || name[i] == 'J' || name[i] == 'K' || name[i] == 'Q' || name[i] == 'S' || name[i] == 'X' || name[i] == 'Z')
encoded += '2';
else if (name[i] == 'D' || name[i] == 'T')
encoded += '3';
else if (name[i] == 'L')
encoded += '4';
else if (name[i] == 'M' || name[i] == 'N')
encoded += '5';
else if (name[i] == 'R')
encoded += '6';
}
return encoded;
}
string removeDuplicate(string encoded) {
for (int i = 0; i < encoded.size(); ++i) {
if (encoded[i] == encoded[i+1])
encoded[i] = '\0';
}
return encoded;
}
string removeZeros(string digits) {
for (int i = 0; i < digits.size(); ++i) {
if (digits[i] == '0')
digits[i] = '\0';
}
return digits;
}
string padding(string output) {
int size = output.size();
if (size < 4) {
for (int i = size; i < 4; ++i)
output += '0';
}
else if (size > 4) {
for (int j = size; j > 3; --j)
output[j] = '\0';
}
return output;
}
/* TODO: Replace this comment with a descriptive function
* header comment.
*/
string soundex(string s) {
/* TODO: Fill in this function. */
string copy = s;
removeNonLetters(s);
encode(s);
removeDuplicate(s);
s[0]= copy[0];
removeZeros(s);
padding(s);
return s;
}
int main() {
string s = "Curie";
cout << soundex(s) << '\n';
// Output should be C600 but I keep getting "Curie."
}
Your functions return the adjusted strings, that's good. But your calling code doesn't use the returned values!
Something like this is what you want.
string soundex(string s) {
/* TODO: Fill in this function. */
string copy = s;
s = removeNonLetters(s);
s = encode(s);
s = removeDuplicate(s);
s[0] = copy[0];
s = removeZeros(s);
s = padding(s);
return s;
}
If you want to change the value of a variable you normally use =. I'm sure you know that but for some reason you forgot because functions are involved.

What are signals in netbeans C++ debugging

Hey guys I'm trying to debug my C++ application (running it produces no errors but also no output) and it gives me a signal caught error at this point.
'Signal received: ? (Unknown signal)'
Trying to continue with the debug gives me this message:
unrecognized or ambiguous flag word \"?\?
no registers
What could cause this?
The error occurs on this line:
if (input.at(i) == 'I') {
input is a string, given it's value by a user input (Roman Numeral)
Which is part of the following code (Converting Roman Numerals to Arabic Numbers):
//converting Roman Numerals to Arabic Numbers
int toArabic() {
//converts input to upper case
transform(input.begin(), input.end(), input.begin(), ::toupper);
int last_digit = 0;
int current_digit = 0;
int arabic = 0;
//checks that input matches desired numerals
for (int i = 0; i < sizeof(input); i++) {
if (input.at(i) == 'I' ||
input.at(i) == 'V' ||
input.at(i) == 'X' ||
input.at(i) == 'L' ||
input.at(i) == 'C' ||
input.at(i) == 'D' ||
input.at(i) == 'M') {
for (int i = 0; i < sizeof(input); i++) {
//Error occurs below
if (input.at(i) == 'I') {
current_digit = 1;
}
if (input.at(i) == 'V') {
current_digit = 5;
}
if (input.at(i) == 'X') {
current_digit = 10;
}
if (input.at(i) == 'L') {
current_digit = 50;
}
if (input.at(i) == 'C') {
current_digit = 100;
}
if (input.at(i) == 'D') {
current_digit = 500;
}
if (input.at(i) == 'M') {
current_digit = 1000;
}
if (last_digit < current_digit && last_digit != 0) {
current_digit -= last_digit;
arabic -= last_digit;
arabic += current_digit;
last_digit = current_digit;
current_digit = 0;
} else {
last_digit = current_digit;
arabic += current_digit;
current_digit = 0;
}
}
} else {
break;
}
}
return arabic;
}
I had this issue in C++ when I was actually reading invalid data which resulted in an Exception being thrown. Seems like NetBeans does not properly show that information when debugging. At least with version 8.1 and cygwin gdb I observed that problem.
Maybe a segmentation fault. Debug and check for NULL or invalid values.

Aborting when trying to reading and writing bmp files c++

this is my first post in stackoverflow.
I write a program that should take a bmp file in input, and black and white it and then write it into the out.bmp.
when I started to write the code, i delete the bmp file format at the end of the name of input and then open it with text editor, then write the code, and the output style is like the input.
when I type ./a.out <in.bmp>out.bmp in terminal, I get an Abort error (Aborted (core dumped)) and when I give the ./a.out < in > out.bmp gimp say to me it is not a bmp file.
here is the code:
// In the Name of God
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <math.h>
#include <sstream>
using namespace std;
bool TypeIsTrue (string type){
if (type == "424d")
return true;
return false;
}
int GrayIt (int b , int g , int r){
return (b + g + r) / 3 ;
}
int ConvertToDec(string hex){
long int dec = 0;
reverse(hex.begin(), hex.end());
for (int i = 0 ; i <hex.size();i++){
if (hex[i] == 'a')
dec = dec + 10 *(pow(16,i));
else if (hex[i] == 'b')
dec = dec + 11 *(pow(16,i));
else if (hex[i] == 'c')
dec = dec + 12 *(pow(16,i));
else if (hex[i] == 'd')
dec = dec + 13 *(pow(16,i));
else if (hex[i] == 'e')
dec = dec + 14 *(pow(16,i));
else if (hex[i] == 'f')
dec = dec + 15 *(pow(16,i));
else
dec = dec + ((hex[i] - '0')*(pow(16,i)));
}
return dec;
}
string ConvertToHex(int dec){
string hex;
int reminded,Divided;
reminded = dec % 16 ;
Divided = dec / 16;
if (Divided == 10){
hex = "a";
}
else if (Divided == 11){
hex = "b";
}
else if (Divided == 12){
hex = "c";
}
else if (Divided == 13){
hex = "d";
}
else if (Divided == 14){
hex = "e";
}
else if (Divided == 15){
hex = "f";
}
else if (Divided == 0){
hex = "0";
}
else if (Divided == 1){
hex = "1";
}
else if (Divided == 2){
hex = "2";
}
else if (Divided == 3){
hex = "3";
}
else if (Divided == 4){
hex = "4";
}
else if (Divided == 5){
hex = "5";
}
else if (Divided == 6){
hex = "6";
}
else if (Divided == 7){
hex = "7";
}
else if (Divided == 8){
hex = "8";
}
else if (Divided == 9){
hex = "9";
}
if (reminded == 10){
hex = hex+"a";
}
else if (reminded == 11){
hex = hex+"b";
}
else if (reminded == 12){
hex = hex+"c";
}
else if (reminded == 13){
hex = hex+"d";
}
else if (reminded == 14){
hex = hex+"e";
}
else if (reminded == 15){
hex = hex+"f";
}
else if (reminded == 0){
hex = hex+"0";
}
else if (reminded == 1){
hex = hex+"1";
}
else if (reminded == 2){
hex = hex+"2";
}
else if (reminded == 3){
hex = hex+"3";
}
else if (reminded == 4){
hex = hex+"4";
}
else if (reminded == 5){
hex = hex+"5";
}
else if (reminded == 6){
hex = hex+"6";
}
else if (reminded == 7){
hex = hex+"7";
}
else if (reminded == 8){
hex = hex+"8";
}
else if (reminded == 9){
hex = hex+"9";
}
return hex;
}
int main (){
vector <string> a;
vector <string> r;
vector <string> g;
vector <string> b;
vector <string> out;
string temp;
int red,green,blue;
while(cin >> temp){
a.push_back (temp);
}
if(!TypeIsTrue(a[0])){
cout<<"The file is not bmp\nRerun program"<<endl;
abort();
}
int phase = 1;
for (int i = 27 ; i < a.size(); i++){ //int i = 27
string first;
string last;
first = a[i].substr(0,2);
last = a[i].substr(2,3);
if(phase == 4)
phase = 1;
if(phase == 1){
b.push_back(first);
g.push_back(last);
phase ++;
// cout<<"push_backed"<<endl;
}
else if(phase == 2){
r.push_back(first);
b.push_back(last);
phase ++;
// cout<<"push_backed"<<endl;
}
else if(phase == 3){
g.push_back(first);
r.push_back(last);
phase ++;
// cout<<"push_backed"<<endl;
}
}
for (int i = 0 ; i <27 ; i++){
out.push_back(a[i]);
}
for(int i = 27 ; i<b.size() ; i++){
blue = ConvertToDec(b[i]);
green = ConvertToDec(g[i]);
red = ConvertToDec(r[i]);
out.push_back ( ConvertToHex( GrayIt (blue , green , red)));
out.push_back ( ConvertToHex( GrayIt (blue , green , red)));
out.push_back ( ConvertToHex( GrayIt (blue , green , red)));
}
int j = 1 ;
for (int i = 0 ; i < 27 ; i++){
cout<< out[i] << " ";
if (j == 8){
cout<<endl;
j = 0;
}
j++;
}
j=1;
bool space = false;
for (int i = 27 ; i < out.size(); i++){
if( i == 27 + 10){
cout<<endl;
j = 1;
}
cout<<out[i];
if (space)
cout<<" ";
j++;
if(j == 17){
cout<<endl;
j = 1 ;
}
space=!space;
}
return 0;
}
You're getting an abort error because you asked for one.
if(!TypeIsTrue(a[0])){
cout<<"The file is not bmp\nRerun program"<<endl;
abort();
}
If your program is designed to have its output redirected, it is very important to send error messages to stderr (and std::cerr or std::clog) and not stdout.
BTW, the type test is failing because BMP files are not text, it makes no sense to read them using cin >> variable.
In addition, there's no guarantee that a[0] even exists. You need to test a.size() first.
if(a.size() < 1 || !TypeIsTrue(a[0])){
cerr << "The file is not bmp\nRerun program\n";
abort();
}

c++ Converting roman numerals to decimals

This program is a part of an exam I just took, that I had to write. I only got this far and couldn't get anywhere. Here is the prompt:"Write a Test Function toDecimal() that converts a roman numeral such as MMLXVII to it's decimal number representation. Use Main() to test the function. The toDecimal() function should have 2 arguments, the string array of roman numerals and a helper function. This helper function will return the numeric value of each of the letters used in roman numbers. Then convert the string arguments as so: Look at the first two characters,if the first is larger, convert the first and add it to the summation, then call the conversion function again with the second value and add both. IF the first character is lesser than the second subtract the first from the second, and add the result to the conversion of the string. without validation it will also convert strings like "IC". VAlidate the string arguement, if there is an error, call the error processing function. Provide at least two error processing functions and test toDecimal() with each. One could be adking the user to correct, the other may correct it."
I,X,C,M cannot be repeated more than 3 times in succession, D,L,V, can never be repeated in succession.I can only be subtracted from V and X,X can only be subtracted from L and C, C can only be subtracted from D and M. V, L, and D can never be subtracted.
I've lost about 2 days worth of sleep on this, tried writing it hundreds of different ways using and breaking the rules. This is the closest I've got on it.
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <cstring>
using namespace std;
bool checker(string roman);
// Adds each value of the roman numeral together
int toDecimal(string, bool* (*function)(string));
int convert(string roman, int i);
int main(){
string roman;
cout << "This program takes a roman numeral the user enters then converts it to decimal notation." << endl;
cout << "Enter a roman numeral: ";
cin >> roman;
transform(roman.begin(), roman.end(), roman.begin(), toupper);
cout << roman << " is equal to " << toDecimal(roman, *checker(roman)) << endl;
}
bool checker(string roman){
int length = roman.length();
for (int count = 0; count < length; count++){
string sub = roman.substr(count, count);
if(sub != "I" || sub != "V" || sub != "X" || sub != "L" || sub != "C" || sub != "D" || sub != "M"){
cout << "Error. Try Again"<< endl;
return false;
}
else if(convert(roman, count) == convert(roman, count-1) && convert(roman, count) == convert(roman, count+1)){
if (convert(roman,count) == 1 || convert(roman,count) == 10 || convert(roman,count) == 100 || convert(roman,count) == 1000)
if(convert(roman, count-1) == convert(roman, count-2) || convert(roman, count+1) == convert(roman, count+2)){
cout << "Error Try again" << endl;
return false;
}
else if (convert(roman,count) == 5 || convert(roman,count) == 50 || convert(roman,count) == 500){
cout << "Error Try again" << endl;
return false;
}
else return true;
}
}
return true;
}
int toDecimal(string s, bool*(checker) (string roman)){
/**map<char, int> roman;
roman['M'] = 1000;
roman['D'] = 500;
roman['C'] = 100;
roman['L'] = 50;
roman['X'] = 10;
roman['V'] = 5;
roman['I'] = 1;*/
checker(s);
int res = 0;
for (int i = 0; i < s.length() - 1; ++i){
int num = convert(s,i);
res += num;
/**if (roman[s[i]] < roman[s[i+1]])
res -= roman[s[i]];
else
res += roman[s[i]];
}
res += roman[s[s.size()-1]];*/}
return res;
}
int convert(string roman, int i){
enum romans {I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000};
int num = 0;
char c = roman[0];
switch(c){
case 'M':
num = M; break;
case 'D':
if(i + 1 != roman.size() && roman[i+1] == 'M'){
num = M - D;break;
}
else
num = D; break;
case 'C':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D'){
if(roman[i+1] == 'M') num = M - C; break;
if(roman[i+1] == 'D') num = D - C; break;
}
else
num = C; break;
case 'L':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D' || roman[i+1] == 'C'){
if(roman[i+1] == 'M') num = M - L; break;
if(roman[i+1] == 'D') num = D - L; break;
if(roman[i+1] == 'C') num = C - L; break;
}
else
num = L; break;
case 'X':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D' || roman[i+1] == 'C'|| roman[i+1] == 'L'){
if(roman[i+1] == 'M') num = M - X; break;
if(roman[i+1] == 'D') num = D - X; break;
if(roman[i+1] == 'C') num = C - X; break;
if(roman[i+1] == 'L') num = C - X; break;
}
num = X; break;
case 'V':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D' || roman[i+1] == 'C'|| roman[i+1] == 'L' || roman[i+1] == 'X'){
if(roman[i+1] == 'M') num = M - V; break;
if(roman[i+1] == 'D') num = D - V; break;
if(roman[i+1] == 'C') num = C - V; break;
if(roman[i+1] == 'L') num = L - V; break;
if(roman[i+1] == 'X') num = X - V; break;
}
num = V; break;
case 'I':
if ( i + 1 != roman.size() && roman[i + 1] != 'I'){
if(roman[i+1] == 'M') num = M - I; break;
if(roman[i+1] == 'D') num = D - I; break;
if(roman[i+1] == 'C') num = C - I; break;
if(roman[i+1] == 'L') num = L - I; break;
if(roman[i+1] == 'X') num = X - I; break;
}
num =1; break;
}
return num;
}
** I have added the help of people on here. This is an edit to show an progress/congress.
This is the code that I use to convert Roman (smaller than 3999) to Integer. You may check if it works for larger numbers.
int romanToInt(string s) {
map<char, int> roman;
roman['M'] = 1000;
roman['D'] = 500;
roman['C'] = 100;
roman['L'] = 50;
roman['X'] = 10;
roman['V'] = 5;
roman['I'] = 1;
int res = 0;
for (int i = 0; i < s.size() - 1; ++i)
{
if (roman[s[i]] < roman[s[i+1]])
res -= roman[s[i]];
else
res += roman[s[i]];
}
res += roman[s[s.size()-1]];
return res;
}
Hope this could help you.
The solution provided by Annie Kim works, but it uses a std::map, querying it several times for the same character, and I fail to see a reason for it.
int convert_roman_digit(char d)
{
switch (d)
{
case 'M': return 1000;
case 'D': return 500;
case 'C': return 100;
case 'L': return 50;
case 'X': return 10;
case 'V': return 5;
case 'I': return 1;
default: throw std::invalid_argument("Invalid digit");
}
}
int roman_to_int(const std::string& roman)
{
int result = 0, last_added = 0;
for (auto it = roman.rbegin(); it != roman.rend(); ++it)
{
const int value = convert_roman_digit(*it);
if (value >= last_added)
{
result += value;
last_added = value;
}
else
{
result -= value;
}
}
return result;
}
Caveat: the function happily accepts some invalid inputs (e.g. IMM) including "negative" numbers (e.g. IIIIIIIIIIIIIX), there are no overflow checks, and it throws. Feel free to improve it.
int romanToInt(string s)
{
unordered_map<char, int> roman;
roman['I'] = 1;
roman['V'] = 5;
roman['X'] = 10;
roman['L'] = 50;
roman['C'] = 100;
roman['D'] = 500;
roman['M'] = 1000;
int num = 0, prev = 0, curr;
for (int i = s.length() - 1; i >= 0; i--)
{
curr = roman[s[i]];
num += (curr >= prev ? 1 : -1) * curr;
prev = curr;
}
return num;
}