3. ทำซ้ำ ๆ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 3-17  โปรแกรมทดสอบมหัศจรรย์ 1089
public class Magic1089 {
  public static void main(String[] args) {
    int a = 0;
    while (true) {
      a++;
      if (a > 999) break;
      int a0 = a % 10;            // หลักหน่วยของ a
      int a1 = (a / 10) % 10;     // หลักสิบของ a
      int a2 = a / 100;           // หลักร้อยของ a
      if (a0 == a2) continue;     // หลักหน่วยเหมือนหลักสิบ ข้ามตัวนี้ ทำตัวต่อไป 
      int b = a0 * 100 + a1 * 10 + a2; // สลับหลักหน่วยกับหลักร้อย 
      int c = Math.abs(b - a);
      int c0 = c % 10;
      int c1 = (c / 10) % 10;
      int c2 = c / 100;
      int d = c0 * 100 + c1 * 10 + c2;
      if ((c + d) != 1089) break; // ถ้าพบตัวที่ไม่เท่า 1089 รีบเลิกได้แล้ว 
    }
    System.out.println("มหัศจรรย์ 1089 เป็น " + (a==1000) );
  }
}
©2009 S.Prasitjutrakul