日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C語言中組成不重復(fù)的三位數(shù)問題_C 語言

作者:吧唧吧唧orz ? 更新時(shí)間: 2022-12-12 編程語言

C語言組成不重復(fù)的三位數(shù)

對于這個問題,我有兩種解決思路

  • 第一種較為簡單
  • 第二種較為復(fù)雜

(1)通用思路:根據(jù)數(shù)組中的數(shù)字自由組合成三位數(shù)

(2)找出最小數(shù)和最大數(shù)并以此為循環(huán)邊界(目的在于縮小循環(huán)的范圍,提高效率),之后根據(jù)不斷循環(huán),將不符合要求的數(shù)字排除,在某些題中會簡便許多

·由1,2,3,4組成的不重復(fù)的三位數(shù)

(1)通用思路

#include <stdio.h>
?
int main()
{
?? ?int a[4]={1,2,3,4};
?? ?int i,j,k,count=0;
?? ?for (i=0;i<4;i++)
?? ?{
?? ??? ?for (j=0;j<4;j++)
?? ??? ?{
?? ??? ??? ?for (k=0;k<4;k++)
?? ??? ??? ??? ?if (i!=j&&i!=k&&k!=j)
?? ??? ??? ??? ?printf("%d\n",a[i]*100+a[j]*10+a[k]);?
?? ??? ?}
?? ?}
?? ?return 0;
}?

(2)排除思路

#include <stdio.h>
?
int main()
{
?? ?int a[3],i,j,k;
?? ?for (i=123;i<=432;i++)
?? ?{
?? ??? ?int word = 1;
?? ??? ?a[0]=i%10;a[1]=i/10%10;a[2]=i/100;
?? ??? ?for (j=0;j<3;j++)
?? ??? ?{
?? ??? ??? ?if (a[j]==1||a[j]==2||a[j]==3||a[j]==4)
?? ??? ??? ?{
?? ??? ??? ?for (k=0;k<3&&j!=k;k++)
?? ??? ??? ?{
?? ??? ??? ??? ?if (a[k]==a[j])
?? ??? ??? ??? ?{
?? ??? ??? ??? ??? ?word = 0;
?? ??? ??? ??? ??? ?break;
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ? ? ?}
?? ??? ? ? else
?? ??? ? ? {
?? ??? ??? ? ? ?word = 0;
?? ??? ??? ? ? ?break;
?? ??? ? ? }
?? ??? ?
? ? ? ? if (word == 0)
?? ??? ??? ?break;
?? ?}
?
?? ??? ?if (word)
?? ??? ?printf("%d\n",i);
?? ?}
?? ?return 0;
}

·某些題(適用于排除思路)

用1,2,3,.....,9組成三位數(shù)abc,def,ghi,每個數(shù)字恰好使用一次,要求 abc:def:ghi=1:2:3.按照“abc def ghi”的格式輸出所有解,每行一個解。

#include <stdio.h>
?
int main()
{
? ? int abc,def,ghi;
? ? int i,k,a[9],word =1;
? ? for (abc=123;abc<=329;abc++)
? ? {
? ? ? ? def = abc * 2;
? ? ? ? ghi = abc * 3;
? ? ? ? a[0]=abc%10;a[1]=abc/10%10;a[2]=abc/100;
? ? ? ? a[3]=def%10;a[4]=def/10%10;a[5]=def/100;
? ? ? ? a[6]=ghi%10;a[7]=ghi/10%10;a[8]=ghi/100;
? ? ? ? for (k=0;k<9;k++)
? ? ? ? {
? ? ? ? ? ? word = 1;
? ? ? ? ? ? for (i=0;i<9&&i!=k;i++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if (a[k]==a[i]||a[i]==0)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? word = 0;
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if (word == 0)
? ? ? ? ? ? break;
? ? ? ? }
? ? ? ? if (word)
? ? ? ? printf("%d,%d,%d\n",abc,def,ghi);
? ? ? ??
? ? }
}

打印1234組成的不重復(fù)三位數(shù)

1、每位數(shù)都遍歷一次,就是個位出現(xiàn)1234,十位出現(xiàn)1234,百位出現(xiàn)1234

2、去重復(fù),個位十位百位不能相等

3、復(fù)合式遍歷,統(tǒng)計(jì)這種遍歷得到了多少回

var count = 0;
for(i=1;i<=4;i++){
    for(j=1;j<=4;j++){
        for(k=1;k<=4;k++){
            if(i!=j && j!=k && k!=i){
            count++;
            console.log(i+""+j+""+k);
            }
        }
    }
}
console.log("這樣的三位數(shù)有"+count+"個");

原文鏈接:https://blog.csdn.net/H20211009/article/details/121714186

欄目分類
最近更新