日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

美图笔试算法题(两个人拿石头判断输赢)

發(fā)布時(shí)間:2023/12/20 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 美图笔试算法题(两个人拿石头判断输赢) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

剛做完美圖的筆試,兩道編程題,第一道比較簡單:找出一串用逗號(hào)隔開的字符串中不重復(fù)的那個(gè)數(shù)。

以下是第二道,時(shí)間有限,很多地方?jīng)]來得及優(yōu)化,整體邏輯應(yīng)該沒錯(cuò)。

question:

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. True for win and false for lose.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

?

解:

public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int sum = scanner.nextInt();//一開始我拿的三種狀況if (chance(sum,1,1)) {System.out.println(true);}else if (chance(sum,2,1)) {System.out.println(true);}else if (chance(sum,3,1)) {System.out.println(true);}else {System.out.println(false);}}/*** * @param surplus 剩余的石頭數(shù)量* @param take_num 這一次拿走的數(shù)量* @param people 1代表是我,2代表是朋友* @return 返回true,則表示我能贏*/private static boolean chance(int surplus,int take_num,int people) {surplus = surplus-take_num;//當(dāng)某人拿完,剩余四塊時(shí),該人贏if (surplus==4) {if (people==1) {return true;}else {return false;}}//當(dāng)某人拿完,剩余數(shù)小于4塊時(shí),另一個(gè)人贏if (surplus<=3) {if (people==1) {return false;}else {return true;}}//此時(shí)剩余的石頭大于4,繼續(xù)拿if (people==1) {//交換人people = 2;//如果是朋友拿,則必須三個(gè)trueif (chance(surplus,1,people)) {if (chance(surplus,2,people)) {if (chance(surplus,3,people)) {return true;}else {return false;}}else {return false;}}else {return false;}}else {people = 1;//如果是我拿,則只需有一個(gè)true即可if (chance(surplus,1,people)) {return true;}else if (chance(surplus,2,people)) {return true;}else if (chance(surplus,3,people)) {return true;}else {return false;}}} }

?

轉(zhuǎn)載于:https://www.cnblogs.com/red-code/p/6720114.html

總結(jié)

以上是生活随笔為你收集整理的美图笔试算法题(两个人拿石头判断输赢)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。