1. 程式人生 > >leetcode--07 --Reverse Integer(逆轉整數)

leetcode--07 --Reverse Integer(逆轉整數)

example != ack sta java pack pre integer urn

* 原題 * Reverse digits of an integer. * Example1: x = 123, return 321 * Example2: x = -123, return -321 * * 題目大意 * 輸入一個整數對其進行翻轉 * *

  

 1 package com.hust0407;
 2 
 3 import java.util.Scanner;
 4 
 5 /**
 6  * Created by huststl on 2018/4/7 10:34
 7  * 輸入一個整數對其進行翻轉
 8  */
 9 public class Main04 {
10     //通過求余數求商法進行操作
11 public static void main(String[] args) { 12 Scanner scan = new Scanner(System.in); 13 while (scan.hasNext()){ 14 int num = scan.nextInt(); 15 System.out.println(reverse(num)); 16 } 17 } 18 19 private static int reverse(int num) { 20 long
tmp = num; 21 //防止結果溢出 22 long result = 0; 23 //余數求商法 24 while (tmp!=0){ 25 result = result * 10 + tmp %10; 26 tmp = tmp/10; 27 } 28 //溢出判斷 29 if(result<Integer.MIN_VALUE || result >Integer.MAX_VALUE){ 30 result = 0;
31 } 32 33 return (int)result; 34 } 35 }

leetcode--07 --Reverse Integer(逆轉整數)