0

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;
};
Gourav Thakur
  • 231
  • 2
  • 3
  • 15
  • If `i = -1` then `~i` is `0`. Seems to be a shortcut to avoid getting an exit from negative index from `s.length - 1` – VLAZ Jul 06 '21 at 15:53
  • Right, it's basically a short way of writing `i >= 0` (in this case) – Pointy Jul 06 '21 at 15:53
  • 1
    I am reminded of the Martin Fowler quote *"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."*. Because who looks at `i >= 0` and thinks to themselves, that's too long – Liam Jul 06 '21 at 15:54
  • 1
    @Liam many times I've been tempted to just fold a one or two lines in a `for` loop. But the clarity of the boring old "count from this number to that other number" is usually better than the shorter code. – VLAZ Jul 06 '21 at 15:56
  • Interestingly, I've spent half of today trying to fix a problem in some code written by someone who has now left my company who seems to have gone out of their way to make their code as complicated as possible with little benefit. I have not called them nice things... :/ – Liam Jul 06 '21 at 16:00
  • @VLAZ Thank you. Another unnecessary complexity which doesn't add value. – Gourav Thakur Jul 06 '21 at 16:03
  • 1
    @GouravThakur to me it's worse because the *bog standard* way to write this loop (end-to-start) is `for (let i = s.length-1; i >= 0; i--)` which already handles what happens if you start with a negative index - the loop is just skipped. Same with the start-to-end `for (let i = 0; i < s.length; i++)` - if `s.length` is zero, you just don't get in the loop. It's symmetrical. No need to reinvent the condition. – VLAZ Jul 06 '21 at 16:09

0 Answers0