date7.19 迴文數
阿新 • • 發佈:2021-07-25
迴文數
問題描述
1221是一個非常特殊的數,它從左邊讀和右邊讀是一樣的,程式設計求出所有這樣的四位十進位制數。
輸出格式
按從小到大的順序輸出滿足條件的四位十進位制數。
思路
求出所有四位十進位制的迴文數,可以通過遍歷四位數來找出千位與個位,百位與十位相等的數即可。也可以換個思路,四位十進位制迴文數,那就只有兩個數在變化,挑出前兩位數,利用for迴圈自增變化,輸出時按照對應位置輸出即可。
程式碼
遍歷四位數
package dailytest; public class d7_19 { public static void main(String[] args) { for(int i = 1000; i < 10000;i++){ int a,b,c,d; a = i/1000; b = (i/100)%10; c = (i/10)%10; d = i%10; if(a == d && b == c){ System.out.println(i); } } } }
通過遍歷所有四位數找到所需要的值,for迴圈次數相對於第二過大。
public class d7_19 {
public static void main(String[] args) {
for(int i = 1;i < 10;i++)
for(int j = 0;j < 10;j++){
System.out.println(""+ i + j + j + i);
}
}
}
這種方法直接得到所需要求的數,沒有太多無效過程。