每日一练34——Java相反的数字(8kyu)

题目

很简单,给定一个数字,找到它的对立面。

例子:

1: -1
14: -14
-34: 34

但是,你能用一行代码完成吗?

测试用例:

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class OppositeExampleTests {
  @Test
  public void tests() {
    assertEquals(-1, Kata.opposite(1));
  }
}

解题

这次和大家一样啦。

public class Kata
    {
        public static int opposite(int number)
        {
            return -number;
        }
    }

其他的:

public class Kata{
  public static int opposite(int number){
    return number * -1;
  }
}
public class Kata
    {
        public static int opposite(int number)
        {
            return Math.negateExact(number);
        }
    }

思考

一开始我还在想复杂的解题思路,什么位运算,补码啥的。但是题目要求一行,那不就是最简单的算术运算吗?

你可能感兴趣的:(每日一练34——Java相反的数字(8kyu))