leetcode007-Reverse Integer

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode007-Reverse Integer相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Algorithms #007 Reverse Integer, Database #182 Duplicate Emails

007. Reverse Integer

No.007:Reverse Integer

[LeetCode] Sequence Reconstruction 序列重建

打败算法 —— 字符串转换整数

LeetCode 107. 二叉树的层序遍历 II