1 /** 2 * 反转正整数 3 */ 4 import java.util.Scanner; 5 6 public class ReverseNumber { 7 public static void main (String[] args) { 8 Scanner input = new Scanner(System.in); 9 System.out.print("输入两位以上的正整数: "); 10 int number = input.nextInt(); 11 int reversedNumber = reverse(number); 12 System.out.println("The reversed number for " + number + " is " + reversedNumber); 13 } 14 15 // 取值解法 16 public static int reverse(int numberP) { 17 int reversedNumber = 0; 18 int temp = 0; 19 int digitsTester = 0; 20 // 计算出numberP是几位的正整数 21 // e.g. i = 10; i < 234; i *= 10 22 for (int i = 10; i < numberP; i *= 10) { 23 // digitsTester = 100 24 digitsTester = i; 25 // if i = 1000 > 234 , digitsTester = 1000 / 10 = 100 26 if (i > numberP) { 27 digitsTester /= 10; 28 // break; 29 } 30 } 31 // 求出100是10的几次方 32 int log10 = (int)Math.log10(digitsTester); 33 while (numberP != 0) { 34 for (int i = 0; i <= log10; i++) { 35 // temp = 234 / 100 = 2 36 temp = numberP / digitsTester; 37 // numberP = 234 / 100 (=2) * 100 = 200 38 numberP = numberP - numberP / digitsTester * digitsTester; 39 // digitsTester = 100 / 10 = 10 40 digitsTester = digitsTester / 10; 41 // reversedNumber = 0 + 2 * 10^0 42 reversedNumber = reversedNumber + temp * (int)Math.pow(10, i); 43 } 44 } 45 return reversedNumber; 46 } 47 }
时间: 2024-10-15 08:13:44