Comparative linguistics
class Solution:
def romanToInt(self, s: str) -> int:
d = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
ret = 0
i = 0
while i < len(s) -1:
if (d[s[i]] < d[s[i+1]]):
ret -= d[s[i]]
else:
ret += d[s[i]]
i+=1
return ret + d[s[i]]
int hash(char c)
{
switch(c)
{
case 'I':
return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break; case 'C':
return 100;
break; case 'D':
return 500;
break; case 'M':
return 1000;
break;
default:
break;
}
return 0;
}
int romanToInt(char* s) {
int ret = 0;
for (int i = 0; i < strlen(s);)
{
if (hash(s[i]) < hash(s[i+1]))
{
ret += (hash(s[i+1]) - hash(s[i]));
i+=2;
}
else
{
ret += hash(s[i]);
i++;
}
}
return ret;
}
all 100%.
- C has no hashtable, so I used switch, which actually hash('\0') as 0.
- len(s) and strlen(s) in Python and C all got a 3.
but in python:
>>> s = "abc"
>>> s[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
printf("%d\n%d", strlen(s), s[4]);
in C, s[3] will printf 0 as %d, and s[4] could be anything but it's accessable. such as 37, whatever.
so in C, I actually access the last char of s as '\0'. But in python, the operator is not safe. but there's also no char type in python.

浙公网安备 33010602011771号