Too many 'if' statements?

前端 未结 26 1171
天涯浪人
天涯浪人 2020-11-30 16:24

The following code does work how I need it to, but it\'s ugly, excessive or a number of other things. I\'ve looked at formulas and attempted to write a few solutions, but I

26条回答
  •  悲&欢浪女
    2020-11-30 16:42

    The shortest and still readable solution:

    static public int fightMath(int one, int two)
    {
        if (one < 2 && two < 2) return 0;
        if (one > 1 && two > 1) return 3;
        int n = (one + two) % 2;
        return one < two ? 1 + n : 2 - n;
    }
    

    or even shorter:

    static public int fightMath(int one, int two)
    {
        if (one / 2 == two / 2) return (one / 2) * 3;
        return 1 + (one + two + one / 2) % 2;
    }
    

    Doesn't contain any "magic" numbers ;) Hope it helps.

提交回复
热议问题