现在有n张扑克牌,每张扑克牌都有点数和花色两部分组成。点数为‘1’-‘9’的正整数,花色为'C','D','H','S''其中的一个,分别表示梅花、方块、红桃、黑桃。现在想按一定的顺序把这n张牌扔掉。扔牌顺序的规则如下1.:
1.如果现在还剩素数张牌,则将牌顶的牌扔掉
2.如果现在还剩非素数张牌,则将牌底的牌扔掉
求扔牌顺序是什么,请返回扔牌顺序的字符串
"3C8D6H3D"
"3D3C8D6H"
开始n=4,为非素数,扔掉牌底的牌3Dn=3,为素数,扔掉牌顶的牌3Cn=2,为素数,扔掉牌顶的牌8Dn=1,为非素数,扔掉牌底的牌6H
"8S8S8S8S8S8S8S"
"8S8S8S8S8S8S8S"
因为全是8S,所以扔牌顺序的每一张牌也都是8S
public String Orderofpoker (String x) { // write code here String ss=""; int n=x.length()/2; while(n>0){ if(isPrime(n)){ ss+=x.substring(0,2); x=x.substring(2); }else{ ss+=x.substring(x.length()-2); x=x.substring(0,x.length()-2); } n--; } return ss; } public boolean isPrime(int n){ if(n==1) return false; if(n==2) return true; for(int i=2;i<n;i++){ if(n%i==0) return false; } return true; }
import java.util.*; public class Solution { public String Orderofpoker (String x) { ArrayList<Integer> table = new ArrayList<>(); table.add(2); table.add(4); table.add(6); table.add(10); table.add(14); StringBuffer resultBuffer = new StringBuffer(); while (x.length() != 0) { if (table.contains(x.length())) { resultBuffer.append(x.substring(0, 2)); x = x.substring(2); } else { resultBuffer.append(x.substring(x.length() - 2)); x = x.substring(0, x.length() - 2); } } String result = resultBuffer.toString(); return result; } }
import java.util.*; public class Solution { public String Orderofpoker (String x) { StringBuffer resultBuffer = new StringBuffer(); while (x.length() != 0) { if (isPrime(x.length() / 2)) { resultBuffer.append(x.substring(0, 2)); x = x.substring(2); } else { resultBuffer.append(x.substring(x.length() - 2)); x = x.substring(0, x.length() - 2); } } String result = resultBuffer.toString(); return result; } private boolean isPrime(int value) { if (value == 1) { return false; } int sqrt = (int) Math.sqrt(value); for (int i = 2; i <= sqrt; i++) { if (value % i == 0) { return false; } } return true; } }
class Solution { public: /** * * @param x string字符串 字符串从前到后分别是从上到下排列的n张扑克牌 * @return string字符串 */ string Orderofpoker(string x) { string str = ""; int len = x.length(); int temp = len/2; int temp2 = temp; int begin = 0; int end = len-1; for(int i=0;i<temp2;i++) { if(judgeprime(temp)) { str += x[begin]; str += x[begin+1]; begin+=2; } else { str += x[end-1]; str += x[end]; end-=2; } temp-=1; } return str; // write code here } bool judgeprime(int num) { if(num==0||num==1) { return false; } int sqr = (int)sqrt(1.0*num); for(int i=2;i<=sqr;i++) { if(num%i==0) { return false; } } return true; } };