zoukankan      html  css  js  c++  java
  • Java逆序输出整数

    题目要求:编写方法reverseDigit,将一个整数作为参数,并反向返回该数字。例如reverseDigit(123)的值是321。同时编写程序测试此方法。

    说明:10的倍数的逆序,均以实际结果为准,如100的逆序为1。此方法也可以实现负数的逆序输出。

     1 import java.util.Scanner;
     2 
     3 public class Test {
     4     static int reverseDigit(int n) {
     5         int result = n, count = 1;        //先将n赋值给result,用count计数以便后续数组操作
     6         while ((result /= 10) != 0) {    //使用while循环,对result进行除10取整操作
     7             count++;                    //如果取整后不为0,则count加一
     8         }
     9         int[] list = new int[count];    //使用数组存放n的每一位,长度为count,注意此处result已经等于0
    10         for (int i = 0; i < count; i++) {    //循环count次
    11             list[i] = n % 10;            //存放n的每一位,从后往前,逆序存放
    12             result += list[i] * Math.pow(10, count - 1 - i); //使用幂运算,底数为10,指数为count-1-i
    13             n = n / 10;                    //n除10取整
    14         }
    15         return result;
    16     }
    17 
    18     public static void main(String[] args) {
    19         int n;
    20         System.out.println("Please input a int:");
    21         Scanner sc = new Scanner(System.in);
    22         n = sc.nextInt();
    23         System.out.printf("The reverse is %d !
    ", reverseDigit(n));
    24         sc.close();
    25     }
    26 }
  • 相关阅读:
    linux开启oracle服务
    一个tomcat多域名绑定多项目
    linux安装jdk1.7.0
    windows 查看端口进程和杀死进程
    windows2008 扩大远程连接数
    windows下用bak文件备份数据库
    linux常用命令
    mysql 开启远程连接访问
    windows 下tomcat安装
    IBM公司面试题
  • 原文地址:https://www.cnblogs.com/linkchen/p/10682572.html
Copyright © 2011-2022 走看看