【发布时间】:2020-06-09 02:56:36
【问题描述】:
我想编写一个函数int returnNthDigit(long long int number, int position) {},使其返回左侧的第 N 个位置数字。例如returnNthDigit(45006, 1); 必须返回 4。同样,returnNthDigit(45006, 2); 必须返回 5。我不允许使用任何循环语句。这是我使用循环提出的一种解决方案。
#include <iostream>
#include <math.h>
int returnNthDigit(long long int number, int position)
{
int numberOfDigits = log10(number) + 1;
int iteration = numberOfDigits - position;
while (iteration != 0)
{
number = number / 10;
--iteration;
}
return number % 10;
}
int main() {
std:: ios_base::sync_with_stdio(false);
std:: cout << returnNthDigit(230045, 5);
return 0;
}
我可以做得更好吗?
【问题讨论】:
-
如果不能使用循环,就必须使用递归。
-
您能否详细说明什么是
loop?因为我们可以进行递归或将数字转换为字符串并执行 charAt()。 -
可以不使用while循环,而是将循环替换为以下 number = number / pow(10,(numberOfDigits - position));
-
如果你被允许知道
long long int的大小,你可以做一个“展开”的二进制切分来找到位数(这似乎是一个棘手的位)。然后用 10 的幂表进行提取。 (顺便说一句,-ve 值呢?)。
标签: c++ algorithm c++11 numbers