在不使用数组的情况下在另一个数字中找到一个数字

find a number in another number without using Array

最近我参加了一次面试,要求我编写一个函数来查找数字中的某个术语及其出现的次数。

假设 term = 51,number = 164518351,所以 51 确实存在 number 并且出现了 2 次,所以 return 2.

我的解决方案 - 将数字和术语转换为字符串 and ,将数字字符串中的术语字符串替换为 "A" 然后最后统计 "A" 在数字字符串中。他让我不使用字符串来解决,所以我给了一个数组的方法。

但是他说我也不能使用数组。所以我想知道是否还有其他方法可以做到这一点?我不想要确切的代码或算法,我只想知道我们可以采用的各种方法来以最小的时间复杂度解决这个问题。

你可以试试这个

int term_count = 0;
while(number > 0){
    if(number % 100 == term)
        term_count++;
    number = number/10
}

这将检查数字的最后两位数字是否等于术语,并继续这样做,忽略数字的每个单位数字。

像这样

164518351 % 100 == 51

16451835 % 100 == 51

1645183 % 100 == 51

164518 % 100 == 51

....

当然,这里我知道术语是两位数,所以我mod乘以100。如果你不知道,你可以找到术语中的位数,然后mod个数

10^(num_of_digits_in_term)

你可以找到这样的位数

int tempTerm = term, termDigitCount = 0;
while(tempTerm > 0){
    termDigitCount++;
    tempTerm /= 10;
}

// 51 > 0 -> termDigitCount = 1
// 1 > 0 -> termDigitCount = 2
// 0 > 0 -> exit while loop

最后如果 term_count 为 0,则数字中没有出现该术语

希望对您有所帮助。

P.S - 解决方案在语法上可能不正确,因为 OP 不需要确切的答案。只是逻辑。