码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode007-Reverse Integer

时间:2017-12-02 00:36:17      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:return   turn   bit   put   code   solution   nbsp   bsp   als   

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

 

Example 2:

Input: -123
Output: -321

 

Example 3:

Input: 120
Output: 21

 

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

Solution:

int reverse(int x) {
  bool negative = false;
  if(x<0){
    negative = true;
    x = -x;
  }
  int nums = 0;
  int tmpNum;
  int tmp;
  int i;
  while(x){
    tmpNum = nums;
    tmp = 0;
    for(i = 0;i<10;i++){
      tmp = tmp+tmpNum;
      if(tmp<tmpNum)
      return 0;
    }
    nums = tmp;
    nums=nums+x%10;
    x = x/10;
  }
  if(negative)
  return -1*nums;
  return nums;
}

 

leetcode007-Reverse Integer

标签:return   turn   bit   put   code   solution   nbsp   bsp   als   

原文地址:http://www.cnblogs.com/silverbulletcy/p/7944867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!