classSolution{public://判断是否是素数boolisPrime(int n){if(n ==1)returnfalse;for(int i =2; i <=sqrt(n); i ++){if(n % i ==0)returnfalse;}returntrue;}//偶数位的肯定不是素数(除了11)。abba 能被11整除//判断是否是回数intget_len(int n){int cnt =0;while(n){
n /=10;
cnt ++;}return cnt;}//判断是否是回数boolreverse(int n){int ans =0;int t = n;while(n){
ans = ans *10+(n %10);
n /=10;}return ans == t;}intprimePalindrome(int n){while(1){if(n >1e7&& n <1e8) n =1e8;// 没有这句就超时if(get_len(n)&1|| n ==11)//奇数位长度, 判断是否回文{if(reverse(n)&&isPrime(n))return n;}
n ++;}return0;}};
classSolution{public:intnthUglyNumber(int n){
priority_queue<longlong, vector<longlong>, greater<longlong>> q;
set<longlong> st;
q.push(1);
st.insert(1);int coeff[3]={2,3,5};for(int i =1;; i ++){longlong x = q.top();
q.pop();if(i == n){return x;}for(int j =0; j <3; j ++){longlong x2 = x * coeff[j];if(!st.count(x2)){
st.insert(x2);
q.push(x2);}}}return0;}};
动态规划
classSolution{public:intnthUglyNumber(int n){int dp[2000];memset(dp,0,sizeof dp);
dp[0]=1;int a =0, b =0, c =0;//通过*2 来获得新丑数的有a个, 通过*3 来获得新丑数有b个, 同理*5 有c个for(int i =1; i < n; i ++){int t1 = dp[a]*2, t2 = dp[b]*3, t3 = dp[c]*5;
dp[i]=min(t1,min(t2, t3));if(dp[i]== t1) a ++;// 第a个数已经通过乘2得到了一个新的丑数,那下个需要通过乘2得到一个新的丑数的数应该是第(a+1)个数if(dp[i]== t2) b ++;//同理if(dp[i]== t3) c ++;//同理}return dp[n -1];}};