当前位置:  首页>> 技术小册>> 数据结构与算法(中)

难度: Easy

内容描述

  1. 给定一个32位有符号整数,求出整数的倒数。
  2. Example 1:
  3. Input: 123
  4. Output: 321
  5. Example 2:
  6. Input: -123
  7. Output: -321
  8. Example 3:
  9. Input: 120
  10. Output: 21

解题方案

思路 1
**- 时间复杂度: O(n)**- 空间复杂度: O(1)**

将整数翻转,翻转后是否溢出了, beats 95.35%

  1. class Solution {
  2. public int reverse(int x) {
  3. // 使用一个long型变量来保存
  4. long index = 0;
  5. while (x != 0){
  6. index = index * 10 + x %10;
  7. x = x / 10;
  8. }
  9. int result = (int) index;
  10. if(result != index){
  11. return 0;
  12. }
  13. return (int)index;
  14. }
  15. }

该分类下的相关小册推荐: