There is a sequence of squares: 149162536 (1 4 9 16 25 36...) How do I get a digit that has a n-number? Example:n = 5, answer 6. n = 2, answer 4. n = 9, answer 6.
The solution seems rather easy with a brute force approach:
i = 0
.i*i
and convert to a string with snprintf
. Let len
be the length of this string.n >= len
increment i
, subtract len
from n
and continue at step 2.n
.Here is some code:
int find_char_in_square_sequence(unsigned long long n) {
for (unsigned long long i = 0;; i++) {
char buf[32];
unsigned int len = snprintf(buf, sizeof buf, "%llu", i * i);
if (n < len)
return buf[n] - '0';
n -= len;
}
}
For large index values, a more efficient approach would handle ranges of values with squares of the same size in a single step, reducing the time complexity from O(N log N) to just above O(log N) .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.