输入一整数123,返回一反转后的整数321

来源:互联网 发布:金融数据分析师累吗 编辑:程序博客网 时间:2024/05/22 15:05

题目: 输入一整数,返回一反转后的整数,如:输入798,返回897;输入-8653,返回-3568.

数组反转之类的见多了,但整数反转却少见,自己试了一下,不知道这方法行不行,代码如下:

package algorithm;import java.util.LinkedList;/** * @author RockeyLu<br> *         输入一整数,返回一反转后的整数,如:输入798,返回897;输入-8653,返回-3568. */public class IntegerInverse {public static void main(String[] args) {// int inputInt = 798;int inputInt = -8653;System.err.println("Input:" + inputInt);int result = inverseInteger(inputInt);System.err.println("result:" + result);}/** * 反转整数 *  * @param inputInt * @return */private static int inverseInteger(int inputInt) {if (inputInt == 0) {return 0;}LinkedList<Integer> tempList = new LinkedList<Integer>();changeIntegerToList(inputInt, tempList);int result = 0;for (int i = 0; i < tempList.size(); i++) {result += tempList.get(i) * Math.pow(10, i);}return result;}/** * 把整数拆分放到集合中去 *  * @param inputInt * @param tempList */private static void changeIntegerToList(int inputInt,LinkedList<Integer> tempList) {int temp1 = inputInt / 10;int temp2 = inputInt % 10;tempList.addFirst(temp2);if (temp1 != 0) {changeIntegerToList(temp1, tempList);}}}