Skip to content

Commit 638aaab

Browse files
authored
Merge pull request #1173 from 0xff-dev/2843
Add solution and test-cases for problem 2843
2 parents 99cbdf9 + 74f98b8 commit 638aaab

File tree

3 files changed

+97
-0
lines changed

3 files changed

+97
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# [2843.Count Symmetric Integers][title]
2+
3+
## Description
4+
You are given two positive integers `low` and `high`.
5+
6+
An integer `x` consisting of `2 * n` digits is **symmetric** if the sum of the first `n` digits of `x` is equal to the sum of the last `n` digits of `x`. Numbers with an odd number of digits are never symmetric.
7+
8+
Return the **number of symmetric** integers in the range `[low, high]`.
9+
10+
**Example 1:**
11+
12+
```
13+
Input: low = 1, high = 100
14+
Output: 9
15+
Explanation: There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99.
16+
```
17+
18+
**Example 2:**
19+
20+
```
21+
Input: low = 1200, high = 1230
22+
Output: 4
23+
Explanation: There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230.
24+
```
25+
26+
## 结语
27+
28+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]
29+
30+
[title]: https://leetcode.com/problems/count-symmetric-integers
31+
[me]: https://github.com/kylesliu/awesome-golang-algorithm
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package Solution
2+
3+
import "fmt"
4+
5+
func Solution(low int, high int) int {
6+
var ok func(int) bool
7+
ok = func(n int) bool {
8+
s := fmt.Sprintf("%d", n)
9+
l := len(s)
10+
if l&1 == 1 {
11+
return false
12+
}
13+
// 1 2, 3, 4
14+
left, right := 0, 0
15+
for start, end := 0, l-1; start < end; start, end = start+1, end-1 {
16+
left += int(s[start] - '0')
17+
right += int(s[end] - '0')
18+
}
19+
return left == right
20+
}
21+
cnt := 0
22+
for i := low; i <= high; i++ {
23+
if ok(i) {
24+
cnt++
25+
}
26+
}
27+
return cnt
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package Solution
2+
3+
import (
4+
"reflect"
5+
"strconv"
6+
"testing"
7+
)
8+
9+
func TestSolution(t *testing.T) {
10+
// 测试用例
11+
cases := []struct {
12+
name string
13+
low, high int
14+
expect int
15+
}{
16+
{"TestCase1", 1, 100, 9},
17+
{"TestCase2", 1200, 1230, 4},
18+
}
19+
20+
// 开始测试
21+
for i, c := range cases {
22+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
23+
got := Solution(c.low, c.high)
24+
if !reflect.DeepEqual(got, c.expect) {
25+
t.Fatalf("expected: %v, but got: %v, with inputs: %v %v",
26+
c.expect, got, c.low, c.high)
27+
}
28+
})
29+
}
30+
}
31+
32+
// 压力测试
33+
func BenchmarkSolution(b *testing.B) {
34+
}
35+
36+
// 使用案列
37+
func ExampleSolution() {
38+
}

0 commit comments

Comments
 (0)