我希望在输入部分键入的情况下,根据范围(min,max)列表检查(数字)输入;换句话说,我需要一种优雅的算法来根据范围检查数字的前缀(不使用正则表达式)。
示例测试用例:
1 is in ( 5, 9) -> false
6 is in ( 5, 9) -> true
1 is in ( 5, 11) -> true (as 10 and 11 are in the range)
1 is in ( 5, 200) -> true (as e.g. 12 and 135 are in the range)
11 is in ( 5, 12) -> true
13 is in ( 5, 12) -> false
13 is in ( 5, 22) -> true
13 is in ( 5, 200) -> true (as 130 is in the range)
2 is in (100, 300) -> true (as 200 is in the range)
你有什么想法吗?
发布于 2012-09-24 21:48:05
bool isInRange(int input, int min, int max)
{
int multiplier = 1;
while(input*multiplier <= max)
{
if(input >= min / multiplier) return true;
multiplier *= 10;
}
return false;
}
它通过了所有测试用例。
发布于 2012-09-24 22:16:12
一种简单的解决方案是在range中生成所有N位前缀。因此,对于11 is in ( 5, 12)
,您需要5到12之间的所有数字的两位前缀。很明显,这只是10,11和12。
一般来说,对于数字X到Y,可能的N位前缀可以通过以下算法获得:
X = MIN(X, 10^(N-1) ) ' 9 has no 2-digit prefix so start at 10
Y = Y - (Y MOD 10^N) ' 1421 has the same 2 digit prefix as 1400
WHILE (X < Y)
LIST_PREFIX += PREFIX(N, X) ' Add the prefix of X to the list.
X += 10^(TRUNCATE(LOG10(X)) - N+1) ' For N=2, go from 1200 to 1300
发布于 2012-09-24 22:39:14
(input >= lower_bound) && input <= upper_bound
OR
(f(input) >= lower_bound) && (f(input) <= upper_bound)
OR
(lower_bound - f(input) < pow(10, n_digits_upper_bound - n_digits_input)) &&
(lower_bound - f(input) > 0)
where
f(input) == (input * pow(10, n_digits_upper_bound - n_digits_input))
1 is in ( 5, 9) -> 1 * pow(10,0) -> same -> false
6 is in ( 5, 9) -> true
1 is in ( 5, 11) -> 1 * pow(10,1) -> 10 is in (5,11) -> true
1 is in ( 5, 200) -> 1 * pow(10,2) -> 100 is in (5, 200) -> true
11 is in ( 5, 12) -> true
13 is in ( 5, 12) -> 13 * pow(10,0) -> same -> false
13 is in ( 5, 22) -> true
13 is in ( 5, 200) -> true
2 is in (100, 300) -> 2 * pow(10,2) -> 200 is in (100,300) -> true
4 is in (100, 300) -> 4 * pow(10,2) -> 400 is in (100,300) -> false
13 is in (135, 140) -> 135 - 130 -> true
14 is in (135, 139) -> 135 - 140 -> false
https://stackoverflow.com/questions/12566251
复制相似问题