Skip to content

Commit

Permalink
feat: 增加 7. 整数反转
Browse files Browse the repository at this point in the history
  • Loading branch information
fxss5201 committed Jul 8, 2024
1 parent 856079a commit b989837
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export default defineConfig({
{ text: '3. 无重复字符的最长子串', link: '/leetcode/longestSubstringWithoutRepeatingCharacters' },
{ text: '5. 最长回文子串', link: '/leetcode/longestPalindromicSubstring' },
{ text: '6. Z 字形变换', link: '/leetcode/zigzagConversion' },
{ text: '7. 整数反转', link: '/leetcode/reverseInteger' },
{ text: '83. 删除排序链表中的重复元素', link: '/leetcode/removeDuplicatesFromSortedList' },
{ text: '2085. 统计出现过一次的公共字符串', link: '/leetcode/countCommonWordsWithOneOccurrence' },
{ text: '2182. 构造限制重复的字符串', link: '/leetcode/constructStringWithRepeatLimit' },
Expand Down
12 changes: 12 additions & 0 deletions docs/leetcode/reverseInteger.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# 7. 整数反转

[7. 整数反转](https://leetcode.cn/problems/reverse-integer/description/)

## 代码

::: code-group

<<< ../../src/leetcode/reverseInteger/javascript.js{javascript} [javascript]
<<< ../../src/leetcode/reverseInteger/typescript.ts{typescript} [typescript]

:::
13 changes: 13 additions & 0 deletions src/leetcode/reverseInteger/javascript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// 输入:x = 123
// 输出:321

export function reverse(x) {
let res = 0
while (x !== 0) {
res = res * 10 + x % 10
x = ~~(x / 10)
const max = Math.pow(2, 31)
if (res < -max || res > max - 1) return 0
}
return res
}
13 changes: 13 additions & 0 deletions src/leetcode/reverseInteger/typescript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// 输入:x = 123
// 输出:321

export function reverse(x: number): number {
let res = 0
while (x !== 0) {
res = res * 10 + x % 10
x = ~~(x / 10)
const max = Math.pow(2, 31)
if (res < -max || res > max - 1) return 0
}
return res
}
7 changes: 7 additions & 0 deletions test/reverseInteger.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { expect, test } from 'vitest'
import { reverse } from '../src/leetcode/reverseInteger/typescript.ts'


test(`123`, () => {
expect(reverse(123)).toEqual(321)
})

0 comments on commit b989837

Please sign in to comment.