首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检查拼写的数字是否在C++的范围内

检查拼写的数字是否在C++的范围内
EN

Stack Overflow用户
提问于 2012-09-24 21:38:48
回答 7查看 3.6K关注 0票数 46

我希望在输入部分键入的情况下,根据范围(min,max)列表检查(数字)输入;换句话说,我需要一种优雅的算法来根据范围检查数字的前缀(不使用正则表达式)。

示例测试用例:

代码语言:javascript
复制
 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)

你有什么想法吗?

EN

回答 7

Stack Overflow用户

发布于 2012-09-24 21:48:05

代码语言:javascript
复制
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;
}

它通过了所有测试用例。

票数 3
EN

Stack Overflow用户

发布于 2012-09-24 22:16:12

一种简单的解决方案是在range中生成所有N位前缀。因此,对于11 is in ( 5, 12),您需要5到12之间的所有数字的两位前缀。很明显,这只是10,11和12。

一般来说,对于数字X到Y,可能的N位前缀可以通过以下算法获得:

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2012-09-24 22:39:14

代码语言:javascript
复制
(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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12566251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档