開始刷題,感覺代碼量和基礎太渣了,導致數據結構不會,重頭慢慢刷吧~
1、題目
輸入樣例:
123
輸出樣例:
1: 321 - 123 = 198
2: 981 - 189 = 792
3: 972 - 279 = 693
4: 963 - 369 = 594
5: 954 - 459 = 495
2、代碼
#include<stdio.h>
int main(){
int N,a=0,b=0,c=0;
scanf("%d",&N);
int max=-1,min=1000,cnt=1;
int temp=N;
int maxDigit, minDigit, midDigit;
while(1){
a=temp/100;
b=temp/10%10;
c=temp%100%10;
if(a>=b && a>=c){
maxDigit = a;
}
else if(b>=a && b>=c){
maxDigit = b;
}
else{
maxDigit = c;
}
if(a<=b && a<=c){
minDigit = a;
}
else if(b<=a && b<=c){
minDigit = b;
}
else{
minDigit = c;
}
midDigit = a+b+c-maxDigit-minDigit;
max = maxDigit*100+midDigit*10+minDigit;
min = minDigit*100+midDigit*10+maxDigit;
temp=max-min;
printf("%d: %d - %d = %d\n",cnt,max,min,temp);
if(temp==0||temp==495) break;
cnt++;
max=-1,min=1000;
}
return 0;
}
3、討論
這個題很有意思的哈,本來以爲就是個 “簡單” 題,用循環來計算最大值最小值,果然超時了。。。
#include<stdio.h>
int main(){
int N,a=0,b=0,c=0;
scanf("%d",&N);
int max=-1,min=1000,cnt=1;
int temp=N;
while(1){
a=temp/100;
b=temp/10%10;
c=temp%100%10;
int n[6]={0};
n[1]=100*a+10*b+c;
n[2]=100*a+10*c+b;
n[3]=100*b+10*a+c;
n[4]=100*b+10*c+a;
n[5]=100*c+10*b+a;
n[6]=100*c+10*a+b;
int i;
for(i=1;i<=6;i++){
if(n[i]>max){
max=n[i];
}
}
for(i=1;i<=6;i++){
if(n[i]<min){
min=n[i];
}
}
temp=max-min;
printf("%d: %d - %d = %d\n",cnt,max,min,temp);
if(temp==0||temp==495) break;
cnt++;
max=-1,min=1000;
}
return 0;
}
上網一搜,新的方法是分別取 a,b,c
的最大值和最小值進行組合,這樣就不用循環了,很好用!
妙啊!!!