我只是把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];
}
}
}
Run Code Online (Sandbox Code Playgroud)
我发了推文链接,康拉德鲁道夫告诉我,我得到最不重要数字的方法是O(n)并且效率不高.
不幸的是,对于非常大的数字来说它是O(n) - 使它成为O(logn),调整while循环以获得更高的10的幂...
我对Big O符号并不太熟悉,但我明白O(n)效率不高?
从我的代码示例中可以看出,我扣除10直到数字长度为一位数,所以我可以比较它以查看哪个后缀合适.我有分区和模数的快速发挥,但无法弄明白.
所以,我的问题是,获得数字中最低位数的最佳方法是什么?
我还在学习,所以请放轻松我:)
谢谢!
"快速发挥分裂和模数,但无法弄明白."
number = number % 10
Run Code Online (Sandbox Code Playgroud)
会做的
如果我们真的为这段代码的效率而烦恼(为什么?)那么
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];
}
Run Code Online (Sandbox Code Playgroud)