输入一个数,输出它的相反数

输入一个带符号的整数,得到它的相反数:

 

例1:

输入: 123
 输出:   321

 

例2:

输入: -123
 输出: -321

 

例3:

输入: 120
 输出: 21


public int reserve(int x){
  int result = 0;
  while(x!=0){
    int tail = x % 10;
    int newResult = result * 10 + tail;
    if((newResult-tail)/10 != result){
      return 0;
    }
    result = newResult;
    x = x / 10;
  }
  return result;
}
posted @ 2018-03-01 10:11  必有谦卑  阅读(3526)  评论(1编辑  收藏  举报