數字啞謎和迴文遊戲,數字啞謎迴文遊戲

來源:互聯網
上載者:User

數字啞謎和迴文遊戲,數字啞謎迴文遊戲

編程之美4.10的兩道題。

第一題:找出合格九位元,每位元互不相同(1~9的某個排列),滿足高n位能被n整除。例如abcdefghi,高兩位ab能被2整除,高三位abc能被3整除,以此類推。

一提到排列,很容易就想到遞迴+回溯,這個方法在面試中使用頻率相當高。1~9這九個數字做一次全排列,合格列印,不合格返回。這裡可以使用一些剪枝,例如第二高位只能是偶數,第四高位只能是偶數,第五高位只能被5整除,第六高位只能是偶數,第八高位只能是偶數,這樣的剪枝大大提高了程式的效能。

<span style="font-size:14px;">void FinANumber(char a[], int len, int index){// 第二個數必須是偶數if (index == 1 && (a[index] - '0') % 2 != 0)return;// 第四個數必須是偶數if (index == 3 && (a[index] - '0') % 2 != 0)return;// 第五個數必須是5的倍數if (index == 4 && (a[index] - '0') % 5 != 0)return;// 第六個數必須是偶數if (index == 5 && (a[index] - '0') % 2 != 0)return;// 第八個數必須是偶數if (index == 7 && (a[index] - '0') % 2 != 0)return;if (index == len){for (int i = 0; i < len; i++){// 前n個數必須被n整除int n = 0;for (int j = 0; j <= i; j++)n = n * 10 + a[j] - '0';if (n % (i + 1) != 0)return;}for (int i = 0; i < len; i++)cout << a[i];cout << endl;return;}// 遞迴+回溯for (int i = index; i < len; i++){char tmp = a[index];a[index] = a[i];a[i] = tmp;FinANumber(a, len, index + 1);tmp = a[index];a[index] = a[i];a[i] = tmp;}}int main(){char a[] = "123456789";FinANumber(a, 9, 0);system("pause");return 0;}</span>


第二題:abcde * f = edcba,找出這樣的abcdef五個數。

窮舉法。使用一個1~9的雜湊表可以記錄哪些數已經被使用,哪些數未被使用,從而判斷是否符合題意。

<span style="font-size:14px;">// 迴文遊戲void Palindrome(){bool isUsed[10];for (int n = 10000; n < 100000; n++){bool flag = true;int copy = n;memset(isUsed, 0, sizeof(isUsed));int reverseNum = 0;// 迴圈求n的反轉數for (int i = 0; i < 5; i++){int tmp = copy % 10;reverseNum = reverseNum * 10 + tmp;copy /= 10;if (isUsed[tmp]){flag = false;break;}elseisUsed[tmp] = true;}if (flag && (reverseNum % n == 0)){int x = reverseNum / n;if (x < 10 && !isUsed[x])cout << n << "*" << x << "=" << reverseNum << endl;}}}int main(){Palindrome();system("pause");return 0;}</span>

參考:
《編程之美》4.10


數字啞謎

A/B/C=5
a/b=5c
A/B-C=12 知c=3
則a/b=15
a-b=84
a=90,b=6
 
怎用java寫個程式判斷數字是否是迴文數字

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("請輸入矩陣1行數:");
String a=sc.nextLine();
boolean b=false;
for(int i=0;i<a.length();i++){
if(a.charAt(i)!=a.charAt(a.length()-i-1)){
b=false;
break;
}else{
b=true;
}
}
if(b){
System.out.println(a+"是迴文");
}else{
System.out.println(a+"不是迴文");
}

}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.