原题
http://www.codewars.com/kata/find-nth-digit-of-a-number
题目
The function findDigit takes two numbers as input,
num
andnth
. It outputs the nth digit ofnum
(counting from right to left).
- Note
Ifnum
is negative, ignore its sign and treat it as a positive value.
Ifnth
is not positive, return-1
.
Keep in mind that42 = 00042
. This means thatfindDigit(42, 5)
would return0
. - Examples
findDigit(5673, 4) returns 5
findDigit(129, 2) returns 2
findDigit(-2825, 3) returns 8
findDigit(-456, 4) returns 0
findDigit(0, 20) returns 0
findDigit(65, 0) returns -1
findDigit(24, -8) returns -1
分析
解决本问题只需要两步:
- 把需要判断的位挪到个位(整除)
- 再把个位数取出(取余)
参考答案
#include <cmath>
using namespace std;
int findDigit(int num, int nth){
return nth <= 0?-1:int(abs(num)/pow(10,nth-1))%10;
}