LeetCode刷题笔录 Reverse Integer
2014-02-15 13:23
253 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
随手写的一个,正常的读出每一位的数字然后反序:
转成字符串可以调用StringBuilder类的reverse函数,属于作弊,不提了。
Example1: x = 123, return 321
Example2: x = -123, return -321
随手写的一个,正常的读出每一位的数字然后反序:
import java.lang.Math; public class Solution { public int reverse(int x) { boolean isNegative = isNegative(x); x = Math.abs(x); int numOfDigits = calDigits(x); int[] digits = new int[numOfDigits]; for(int i = 0; i < numOfDigits; i++){ digits[i] = x % 10; x /= 10; } int result = 0; int pow = pow(10, numOfDigits - 1); for(int i = 0; i < numOfDigits; i++){ result += digits[i] * pow; pow /= 10; } if(isNegative){ result = -result; } return result; } public int pow(int a, int b){ int result = a; if (b == 0) { return 1; } for(int i = 1; i < b; i++){ result *= a; } return result; } public boolean isNegative(int x){ if(x < 0) return true; else return false; } public int calDigits(int x){ int numOfDigits = 1; while(x > 10){ numOfDigits++; x /= 10; } return numOfDigits; } }
转成字符串可以调用StringBuilder类的reverse函数,属于作弊,不提了。
相关文章推荐
- LeetCode刷题笔录Search a 2D Matrix
- LeetCode刷题笔录Best Time to Buy and Sell Stock
- LeetCode——Reverse Integer
- LeetCode:Reverse Integer
- Leetcode5: Reverse Integer
- LeetCode 7:Reverse Integer
- [Leetcode]#7 Reverse Integer
- LeetCode:Reverse Integer
- LeetCode:Reverse Integer
- 【JAVA、C++】LeetCode 007 Reverse Integer
- LeetCode_Reverse Integer
- Leetcode 编程训练笔记-Reverse Integer
- Leetcode: Reverse Integer
- 开始刷leetcode day5:Reverse Integer
- LeetCode-Reverse Integer
- LeetCode | Reverse Integer
- [leetcode][大数] Reverse Integer
- LeetCode刷题笔录N-Queens II
- [leetcode] 7 reverse integer
- LeetCode刷题笔录 Pascal's Triangle II