思考一個問題:四位數中,有種特別的數字是 它乘上某個數 能得到它的顛倒四位數
例如:1234 * x = 4321
假設x是原本的四位數、y是顛倒後的四位數、z是某個位數
運算式子:x*z=y
---
程式設計:
step1. 取得y,即思考如何將x顛倒(在此我們不使用陣列,而是透過運算方法取得)
step2. "%"是取得餘數的運算子,可以透過%10得到數字的個位數
Step3. 運用for迴圈從將x從1000找到9999,每次都運算出y
step4. 再找z從2找到9,只要x*z==y即找到
package p00102;
public class c001 {
public static void main(String[] a)
{
int x, y, z;
for(x=1000;x<=9999;x++)
{
int p1,p2,p3,p4;/*P4 is MSD, p1 is LSD*/ (MSD是最高位十進位顯示位元、LSD是最低位十進位顯示位元)
p1 = x%10;
p2 = ((x-p1)/10)%10;
p3 = ((x-p1-p2*10)/100)%10;
p4 =((x-p1-p2*10-p3*100)/1000)%10;
y = p1*1000 + p2*100 + p3*10 + p4;
for(z = 2;z<=10;z++)
{
if(x * z == y)
System.out.println(x+"*"+z+"="+y );
}
}
}
}
將此四位數數字顛倒功能製作成Function
package p00102;
/*Function*/
public class c001c {
public static int Inverse(int x)
{
int y,p1,p2,p3,p4;/*P4 is MSD, p1 is LSD*/
p1 = x%10;
p2 = ((x-p1)/10)%10;
p3 = ((x-p1-p2*10)/100)%10;
p4 =((x-p1-p2*10-p3*100)/1000)%10;
y = p1*1000 + p2*100 + p3*10 + p4;
return(y);
}
public static void main(String[] a)
{
int x, y, z;
for(x=1000;x<=9999;x++)
{
y = Inverse(x);
for(z = 2;z<=10;z++)
{
if(x * z == y)
System.out.println(x+"*"+z+"="+y );
}
}
}
}
最後將Function拉進自己自製的Function Library
此學期的Java Library名稱用fun,所以呼叫時是用fun.XXX (Java物件導向時是用mylib)
本次製作的Function叫Inverse,功能是將任意四位數順序顛倒
package p00102;
/*fun = function, Library */
public class fun {
public static int Inverse(int x)
{
int y,p1,p2,p3,p4;/*P4 is MSD, p1 is LSD*/
p1 = x%10;
p2 = ((x-p1)/10)%10;
p3 = ((x-p1-p2*10)/100)%10;
p4 =((x-p1-p2*10-p3*100)/1000)%10;
y = p1*1000 + p2*100 + p3*10 + p4;
return(y);
}
}
---
運用fun來呼叫Function(函式)
package p00102;
/*library*/
public class c001d {
public static void main(String[] a)
{
int x, y, z;
for(x=1000;x<=9999;x++)
{
y = fun.Inverse(x);
for(z = 2;z<=10;z++)
{
if(x * z == y)
System.out.println(x+"*"+z+"="+y );
}
}
}
}
留言列表