简体   繁体   English

如何计算正方形序列中数字的个数

[英]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?有一个正方形序列: 149162536 (1 4 9 16 25 36...) 我如何得到一个有 n 数的数字? Example:n = 5, answer 6. n = 2, answer 4. n = 9, answer 6.示例:n = 5,回答 6。n = 2,回答 4。n = 9,回答 6。

The solution seems rather easy with a brute force approach:使用蛮力方法,解决方案似乎相当简单:

  1. start with i = 0 .i = 0开始。
  2. compute i*i and convert to a string with snprintf .计算i*i并使用snprintf转换为字符串。 Let len be the length of this string.len为该字符串的长度。
  3. if n >= len increment i , subtract len from n and continue at step 2.如果n >= len increment i ,从n中减去len并继续执行步骤 2。
  4. otherwise, return the character of the string at offset n .否则,返回偏移量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) .对于较大的索引值,更有效的方法将在单个步骤中处理具有相同大小的平方的值范围,从而将时间复杂度从O(N log N)降低到略高于O(log N)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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