Java硬幣翻轉倍數遞增試算執行個體_java

來源:互聯網
上載者:User

//有何不足或者問題希望能夠得到各位的多多指正,不勝感激

複製代碼 代碼如下:

import java.util.Scanner;

/**
 *
 * @author cc 舉例 100枚硬幣,最初全部朝下,第一次將所有硬幣反轉過來, 第二次反轉位置是2的倍數的硬幣,
 *         第三次反轉3的倍數,.....執行一百次,問最終共有多少個硬幣面朝上?
 *
 *         1.硬幣正反使用數組 1、0表示,1表示正面,0表示反面;
 *        
 *        
 *         100枚硬幣的結果
int[] ==  1100100001000000100000000100000000001000000000000100000000000000100000000000000001000000000000000000
  result coin about 1 nums = 10
 */
public class CoinTurn {

 private static int[] intCoins;

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int coinNum = inputNum();
  intCoins = new int[coinNum];

  /*
   * 初始化
   */
  for (int i = 0; i < intCoins.length; i++) {
   intCoins[i] = 0;// 初始化全部朝下,即背面0
  }

  doTurnCoin();

  int resutltCoin = getCoinNum();

  System.out.println("result coin about 1 nums = " + resutltCoin);// 輸出最終正面朝上的個數

 }

 private static void doTurnCoin() {
  /*
   * 翻轉操作
   */
  for (int i = 1; i < intCoins.length; i++) {// 確定倍數

   for (int j = i - 1; j < intCoins.length; j++) {// 迴圈翻轉
    if (j % i == 0) { // 硬幣序列數是當前次數的倍數,則翻轉
     if (intCoins[j] == 0) {
      intCoins[j] = 1;
     } else {
      intCoins[j] = 0;
     }
    }

   }
  }
 }

 private static int getCoinNum() {
  int countNum = 0;// 記錄最終硬幣正面個數
  StringBuffer strB = new StringBuffer();
  for (int a : intCoins) {
   strB.append(a + "");
   if (1 == a)
    countNum++;
  }
  System.out.println("int[] ==  " + strB);// 輸出數組的結果
  return countNum;
 }

 /*
  * coin number
  */
 private static int inputNum() {
  System.out.println("input coin num: ");
  Scanner input = new Scanner(System.in);
  return input.nextInt();
 }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.