gpt4 book ai didi

c - 查找和打印两个给定长整数共有的数字的算法

转载 作者:太空宇宙 更新时间:2023-11-04 05:48:12 24 4
gpt4 key购买 nike

请帮助我在不使用数组的情况下使用适当的 C 算法。

例子:

输入

123456789

2037

输出

常用数字有2、3、7。

我失败的尝试:

long a, b, original_a, original_b;
int i, j, figure_a, figure_b;

printf("a=");
scanf_s("%li", &a);
printf("b=");
scanf_s("%li", &b);

original_a = a;
original_b = b;

for (i = 0; i <= 9; i++)
for (j = 0; j <= 9; j++){
a = original_a;
b = original_b;

while (a||b){
figure_a = a % 10;
figure_b = b % 10;

a /= 10;
b /= 10;

if (i == figure_a && j == figure_b && i == j)
printf("%d, ", i);
}

}

最佳答案

您可以将两个整数都转换为字符串,然后将第一个字符串的每个字符与第二个字符串进行比较,以检查它们是否匹配。我使用嵌套的 for 循环进行比较。

我使用字符串是因为比较两个字符串的每个字符比比较两个整数的每个数字要容易得多。

#include <stdio.h>
int main()
{
long int a,b;
int i,j;

scanf("%ld %ld",&a,&b); //taking both inputs

char temp_a[50],temp_b[50];


sprintf(temp_a, "%ld", a); //converting the first integer to a string
sprintf(temp_b, "%ld", b); //converting the second integer to a string


int length_a=strlen(temp_a); //length of first string
int length_b=strlen(temp_b); //length of second string

// matching whether any character is in common using nested for-loops
// printing the character as soon as it matches
// if a character matches, the loop breaks.

for(i=0 ; i<length_a ; i++)
{
for(j=0 ; j<length_b ; j++)
{
if(temp_a[i]==temp_b[j])
{
printf("%c",temp_a[i]);
break;
}
}
}
}

关于c - 查找和打印两个给定长整数共有的数字的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com