-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path374.猜数字大小.cs
110 lines (106 loc) · 2.13 KB
/
374.猜数字大小.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* @lc app=leetcode.cn id=374 lang=csharp
*
* [374] 猜数字大小
*
* https://leetcode-cn.com/problems/guess-number-higher-or-lower/description/
*
* algorithms
* Easy (51.81%)
* Likes: 172
* Dislikes: 0
* Total Accepted: 91.1K
* Total Submissions: 175.9K
* Testcase Example: '10\n6'
*
* 猜数字游戏的规则如下:
*
*
* 每轮游戏,我都会从 1 到 n 随机选择一个数字。 请你猜选出的是哪个数字。
* 如果你猜错了,我会告诉你,你猜测的数字比我选出的数字是大了还是小了。
*
*
* 你可以通过调用一个预先定义好的接口 int guess(int num) 来获取猜测结果,返回值一共有 3 种可能的情况(-1,1 或
* 0):
*
*
* -1:我选出的数字比你猜的数字小 pick < num
* 1:我选出的数字比你猜的数字大 pick > num
* 0:我选出的数字和你猜的数字一样。恭喜!你猜对了!pick == num
*
*
* 返回我选出的数字。
*
*
*
* 示例 1:
*
*
* 输入:n = 10, pick = 6
* 输出:6
*
*
* 示例 2:
*
*
* 输入:n = 1, pick = 1
* 输出:1
*
*
* 示例 3:
*
*
* 输入:n = 2, pick = 1
* 输出:1
*
*
* 示例 4:
*
*
* 输入:n = 2, pick = 2
* 输出:2
*
*
*
*
* 提示:
*
*
* 1
* 1
*
*
*/
// @lc code=start
/**
* Forward declaration of guess API.
* @param num your guess
* @return -1 if num is lower than the guess number
* 1 if num is higher than the guess number
* otherwise return 0
* int guess(int num);
*/
public class Solution : GuessGame {
public int GuessNumber(int n) {
int a = 1;
int b = n;
while(a < b) {
int num = a / 2 + b / 2;
if (a % 2 == 1 && b % 2 == 1) {
num += 1;
}
int result = guess(num);
if (result == 0) {
return num;
}
if (result == 1){
a = num + 1;
}
if (result == -1){
b = num;
}
}
return a;
}
}
// @lc code=end