在C中查找不使用数组的最长数字序列



我正在学习C编程课程,我的任务之一是编写一个程序,从标准输入读取一个整数,并打印到标准输出,出现在最长连续序列中的数字。如果有多个连续的最长序列,请打印最小的数字。1需要注意的是,我们不允许使用数组来解决这个问题。

输入/输出示例:输入1122/输出1、输入800100022/输出0

我已经创建了一个函数来迭代输入数字,识别最长的序列并返回相应的数字,但我不确定为什么这种算法在某些情况下不起作用。我需要一些帮助来识别代码中的一些逻辑缺陷。非常感谢

long get_digit(long n) {
long prev_digit = 0;
long freq = 0;
long max_freq;
long most_freq_digit = 0;
//flag to symbolise first iteration
long flag = 0;
while (n > 0) {
if (flag == 0) {
freq += 1;
most_freq_digit = n % 10;
} else {
if (n % 10 == prev_digit) {
freq += 1;
}
if (n % 10 != prev_digit || n < 10) {
if (freq > max_freq) {
max_freq = freq;
most_freq_digit = prev_digit;
} else
if (freq == max_freq) {
if (prev_digit <= most_freq_digit) {
most_freq_digit = prev_digit;
}
}
freq = 1;
}
}
flag += 1;
prev_digit = n % 10;
n = n / 10;
}
return most_freq_digit;
}

您的代码中存在多个问题:

  • 您没有初始化max_freq,因此整个函数具有未定义的行为
  • flag(n % 10 != prev_digit || n < 10)上更新max_freqmost_freq_digit的测试很麻烦:您可以通过处理循环外的第一个数字来简化逻辑
  • 你不能处理负数

这里有一个更简单的版本:

long get_digit(long n) {
long div = n < 0 ? -10 : 10;
long freq = 1;
long digit = n % div;
long max_freq = freq;
long most_freq_digit = digit;
while (n != 0) {
if (n % div == digit) {
freq += 1;
} else {
digit = n % div;
freq = 1;
}
if (freq > max_freq || (freq == max_freq && digit < most_freq_digit)) {
max_freq = freq;
most_freq_digit = digit;
}
n = n / 10;
}
return most_freq_digit;
}

我想这是你的答案这两个函数分别提供最小的数字和最大的

主要算法是这个

  1. 通过10获取数字的mod并存储在temp中
  2. 把数字除以10
  3. 获取新的mod并与temp进行比较,如果是较小的,请交换它们
  4. 一直到数字为0
int getSmallestDigit(int num) {
int smallest;
int temp;
smallest = num % 10;
num /= 10;
while (num > 0) {
temp = num % 10;
if (temp < smallest) {
smallest = temp;
}
num /= 10;
}
return smallest;
}
int getLargestDigit(int num) {
int large;
int temp;
large = num % 10;
num /= 10;
while (num > 0) {
temp = num % 10;
if (temp > large) {
large = temp;
}
num /= 10;
}
return large;
}

最新更新