![](/img/trans.png)
[英]What is the most portable way to read and write the highest bit of an integer in C?
[英]What is the best way to get right most number in an integer with C?
我只是以C作为学习者,然后编写了这个小函数 ...
char *getPlaceSuffix(int number) {
static char *suffixes[] = {"st", "nd", "rd", "th"};
if (number >= 11 && number <= 13) {
return suffixes[3];
} else {
while (number > 10) {
number -= 10;
}
if (number >= 1 && number <= 3) {
return suffixes[number - 1];
} else {
return suffixes[3];
}
}
}
我在推特上发布了链接, 康拉德·鲁道夫 ( Konrad Rudolph)告诉我,获取最小有效数字的方法是O(n),效率不高。
不幸的是,它的O(n)数量非常大–要使其成为O(logn),请调整while循环以获得更高的10的幂…
我对Big O表示法不太熟悉,但是我知道O(n)不太有效吗?
从代码示例中您可以看到,我减去10直到数字为一位数长,因此可以对其进行比较以查看哪个后缀合适。 我对除法和模数有快速的了解,但无法弄清楚。
因此,我的问题是,获取数字中最低有效位数的最佳方法是什么?
我还在学习,所以请放轻松我:)
谢谢!
number % 10
应该管用。
“可以快速处理除法和模数,但无法弄清楚。”
number = number % 10
会做的
如果我们真的对这段代码的效率感到困扰(为什么?),那么
char *getPlaceSuffix(int number) {
static char *suffixes[] = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
int h = number %100;
int d = number %10
return (h == 11 or h == 12 or h == 13)? suffixes[0]:suffixes[d];
}
如果number
为正,则number = number % 10;
与while (number >= 10) number -= 10;
具有相同的效果while (number >= 10) number -= 10;
。 请注意,我使用的是>=
,而不是您的代码中的>
。
因此,涵盖因模数而得到0
的情况,您应该会很好。
[编辑:哎呀,您的代码已经可以处理0
,正确选择了th
。 很好。 您尝试了什么模数编码?]
“我知道O(n)不太有效吗?”
您的代码效率不高。 O(n)表示在极限中,随着n
接近无穷大,您的代码所花费的时间不会比与n
成正比。 实际上,我们实际上不需要担心无穷大的限制,也不必担心边界-您的循环执行的次数大约与n
成正比。
在这种情况下,由于存在更快的解决方案,因此效率低下。 根据定义,O(1)的解决方案也是O(n),因此O(n)实际上不是“低效”的意思,因为它指定了时间的上限,而不是下限。 但是请注意,该符号被广泛滥用。 人们通常说“ O(n)”是指某种算法在说“Ω(n)”或“Θ(n)”时所花费的时间至少与n成正比。
模量:
number = number % 10;
您在网站上发布的功能不正确。 如果我们通过113,它将返回什么?
char *getPlaceSuffix(int number) {
static char *suffixes[] = {"th", "st", "nd", "rd"};
if (number >= 11 && number <= 13) { return suffixes[0]; }
else {
number %= 10;
if (number >= 1 && number <= 3) { return suffixes[number]; }
else { return suffixes[0]; }
}
}
113将被修改为10,将得到3,然后它将返回后缀[3],即“ rd”。
113应该是113,而不是113(我假设它发音为“一百thirturd” –很有趣,但不正确。)
该函数的读取方式如下:
char *getPlaceSuffix(int number) {
static char *suffixes[] = {"th", "st", "nd", "rd"};
if (number>100) number %= 100;
if (number >= 11 && number <= 13) { return suffixes[0]; }
else {
number %= 10;
if (number >= 1 && number <= 3) { return suffixes[number]; }
else { return suffixes[0]; }
}
}
if (number>100) number %= 100;
应该使该函数返回正确的答案。
您能拿这个数字并将其修改为10,这是您最不重要的数字吗? 当您减去10直到不能再减去时,您正是模数的意思。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.