演算法---將一個整數反轉(簡單)
阿新 • • 發佈:2018-12-26
public class ReverseInteger { /*Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321*/ public static void main(String[] args) { reverseMethod(123456); reverseMethod(12345); } public static void reverseMethod(Integer a) { String s = Integer.toString(a); char[] chars = s.toCharArray(); for (int i = 0; i < chars.length / 2; i++) { chars[i] = (char) (chars[chars.length - 1 - i] + chars[i]); chars[chars.length - 1 - i] = (char) (chars[i] - chars[chars.length - 1 - i]); chars[i] = (char) (chars[i] - chars[chars.length - 1 - i]); } for (int i = 0; i < chars.length; i++) { System.out.println(chars[i]); } } }