We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
7. 整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123 输出: 321
示例 2:
输入: -123 输出: -321
示例 3:
输入: 120 输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
The text was updated successfully, but these errors were encountered:
解法一:
/** * @param {number} x * @return {number} */ var reverse = function(x) { const border = 2**31 const max = border - 1 const min = -border const result = (x > 0 ? 1 : -1) * String(x).split('').filter(x => x !== '-').reverse().join('') return result > max || result < min ? 0 : result };
解法二:
/** * @param {number} x * @return {number} */ var reverse = function(x) { var max = Math.pow(2, 31) - 1; var min = -Math.pow(2, 31); var y = 0; while(x !== 0) { y = 10 * y + x % 10; x = ~~(x/10); } if (y > max) return 0; if (y < min) return 0; return y; };
Sorry, something went wrong.
保存是否为负数,转字符串,排序,再依据保存的是否为负数的状态转回数值
/** * @param {number} x * @return {number} */ var reverse = function(x) { var overflow = function(x) { return x >= Math.pow(2, 31) - 1 || x <= -Math.pow(2, 31) ? 0 : x; } var isNegative = x < 0; var arr = (isNegative ? -x : x).toString().split(''); arr.reverse(); var res = parseInt(arr.join('')); res = isNegative ? -res : res; res = overflow(res); return res; };
No branches or pull requests
7. 整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
示例 2:
示例 3:
注意:
The text was updated successfully, but these errors were encountered: