I am practising few questions for my Interview preparations. While trying to solve a problem where we have to find the integer value of the given roman equivalent, I came across this solution. I can't figure out what does ~i do. What can be its alternative?
What I tried? I tried reading articles about this bit NOT operator(~) but couldn't understand its purpose in this code.
Here's the link to the problem statement: https://leetcode.com/problems/roman-to-integer
var romanToInt = function (s) {
const roman = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
let ans = 0;
for (let i = s.length - 1; ~i; i--) {
let num = roman[s.charAt(i)];
if (4 * num < ans) ans -= num;
else ans += num;
}
return ans;
};