简体   繁体   中英

How to count the number of a digit in a sequence of squares

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:

  1. start with i = 0 .
  2. compute i*i and convert to a string with snprintf . Let len be the length of this string.
  3. if n >= len increment i , subtract len from n and continue at step 2.
  4. otherwise, return the character of the string at offset 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM