学以致用——Java源码——16位以内任意整数的逆序数的输出(Reversing Digits)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hpdlzu80100/article/details/85227820

这道题其实并不简单,涉及:

1. 整数位数的计算

2. 整数各个位数的值的计算

3. 整数的构成

遗留问题:Java long数据类型最大支持Long.MAX_VALUE = 9223372036854775807(共19位),但经过测试,本程序仅支持16位以内的计算,超过后会发生溢出而导致逆序结果不正确。留待以后细究。

package exercises.ch6Methods;

import static java.lang.Math.pow;
import java.util.*;

//JHTP Exercise 6.26 (Reversing Digits)
//by [email protected]
/**
 * 
 *6.26(Reversing Digits) Write a method that takes an integer value and returns the 
 *number with its digits reversed. For example, given the number 7631, the method should 
 *return 1367. Incorporate the method into an application that reads a value from the user 
 *and displays the result.
 *
 */
public class ReverseDigits {
public static void main(String args[]) {
	long input;
	
    Scanner scan=new Scanner(System.in);
    
    do {
    System.out.printf("请输入一个整数(输入-1退出,最大支持16位任意整数):");
    input = scan.nextLong();
    long digits = input;
    long counter = 0;
    long reversed = 0;
    
    //计算该整数的位数(不断除以10,直到小于10为止,运算次数即为该整数的位数,如123,除以10的结果依次为12,1,0,共计算了3次)
    while (digits > 0){
           digits = digits/10;
            counter = counter + 1;
        }
    System.out.printf("该整数共有%d位%n",counter);
    
    //计算该整数的逆序数(通过求余数运算计算)
    System.out.println("该整数逆序数的计算过程:");    
    while (input >0){ 
            reversed =(long)( reversed + input%10*pow(10,counter-1));
            System.out.println(reversed);
            input = input/10;
            counter--;
        }
    System.out.print("该整数的逆序数为:");
    System.out.println(reversed);
    System.out.println();
    } while (input != -1);
    System.out.println("已退出程序。");
    scan.close();
}
}

运行结果:

请输入一个整数(输入-1退出,最大支持16位任意整数)1234567891234567

该整数共有16

该整数逆序数的计算过程:

7000000000000000

7600000000000000

7650000000000000

7654000000000000

7654300000000000

7654320000000000

7654321000000000

7654321900000000

7654321980000000

7654321987000000

7654321987600000

7654321987650000

7654321987654000

7654321987654300

7654321987654320

7654321987654321

该整数的逆序数为:7654321987654321

参考文章:

本程序的核心算法参考了以下链接:

https://stackoverflow.com/questions/15349723/reversing-an-integer-in-java-using-a-for-loop 

猜你喜欢

转载自blog.csdn.net/hpdlzu80100/article/details/85227820