Java逆序输出整数

Java逆序输出整数

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

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

import java.util.Scanner;

public class Test {
	static int reverseDigit(int n) {
		int result = n, count = 1;		//先将n赋值给result,用count计数以便后续数组操作
		while ((result /= 10) != 0) {	//使用while循环,对result进行除10取整操作
			count++;					//如果取整后不为0,则count加一
		}
		int[] list = new int[count];	//使用数组存放n的每一位,长度为count,注意此处result已经等于0
		for (int i = 0; i < count; i++) {	//循环count次
			list[i] = n % 10;			//存放n的每一位,从后往前,逆序存放
			result += list[i] * Math.pow(10, count - 1 - i); //使用幂运算,底数为10,指数为count-1-i
			n = n / 10;					//n除10取整
		}
		return result;
	}

	public static void main(String[] args) {
		int n;
		System.out.println("Please input a int:");
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		System.out.printf("The reverse is %d !\n", reverseDigit(n));
		sc.close();
	}
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值