還是A+B HDU - 1229(數學題)
以k為迴圈變數
#include <stdio.h>
int main()
{
int a, b, k;
while(~scanf("%d %d %d", &a, &b, &k))
{
if(a == 0 && b == 0)
break;
int tmp = a + b;
int t1 = 0, t2 = 0;
bool flag = true;
for(int i = 0; i < k; i++)
{
t1 = a % 10;
t2 = b % 10;
if(t1 != t2)
{
flag = false;
break;
}
a = a / 10;
b = b / 10;
}
if(flag)
printf("-1\n");
else
printf("%d\n", tmp);
}
return 0;
}
以a和b為迴圈變數
#include <stdio.h>
int main()
{
int a, b, k;
while(scanf("%d %d %d", &a, &b, &k))
{
if(!a && !b)
break;
int ans = a + b;
int tmpa, tmpb = 0;
bool flag = true;
while(a || b)
{
tmpa = a % 10;
a /= 10;
tmpb = b % 10;
b /= 10;
k--;
if(tmpa == tmpb)
{
if(k == 0)
{
flag = true;
break;
}
}
if(tmpa != tmpb)
{
//123 4123 3這種情況此時應該輸出-1
if(k < 0)
flag = true;
else
flag = false;
break;
}
}
if(flag)
printf("-1\n");
else
printf("%d\n", ans);
}
return 0;
}