https://leetcode.com/problems/largest-palindrome-product/description/
long getCandidate(int n) {
string s = to_string(n);
reverse(s.begin(), s.end());
return stol(to_string(n) + s);
}
int largestPalindrome(int n) {
if(n==1) return 9;
int mx = pow(10,n) - 1;
int mi = pow(10,n-1);
for(int i=mx; i>=mi; i--) {
long c = getCandidate(i);
for(long j=mx; j*j>=c; j--) {
if(c%j == 0 && c/j >= mi) {
return c%1337;
}
}
}
return -1;
}
Showing posts with label Overflow. Show all posts
Showing posts with label Overflow. Show all posts
Tuesday, September 26, 2017
Wednesday, September 20, 2017
278. First Bad Version
https://leetcode.com/problems/first-bad-version/description/
int firstBadVersion(int n) {
int lo = 1, hi = n;
while(lo<hi){
int mid = lo +(hi - lo)/2;
if(isBadVersion(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
int firstBadVersion(int n) {
int lo = 1, hi = n;
while(lo<hi){
int mid = lo +(hi - lo)/2;
if(isBadVersion(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
Saturday, September 9, 2017
374. Guess Number Higher or Lower
https://leetcode.com/problems/guess-number-higher-or-lower/description/
Solution 1. Recursion.
int guessing(int lo, int hi) {
int mi = (hi - lo)/2 + lo;
int c = guess(mi);
if(c==0) return mi;
else if(c==1) return guessing(mi+1, hi);
else return guessing(lo, mi-1);
}
int guessNumber(int n) {
return guessing(1, n);
}
Solution 2. Iteration.
int guessNumber(int n) {
int mi, re, hi = n, lo = 1;
while(true) {
mi = (hi - lo)/2 + lo;
re = guess(mi);
if(re == 0) return mi;
else if(re == 1) lo = mi + 1;
else hi = mi - 1;
}
}
Solution 1. Recursion.
int guessing(int lo, int hi) {
int mi = (hi - lo)/2 + lo;
int c = guess(mi);
if(c==0) return mi;
else if(c==1) return guessing(mi+1, hi);
else return guessing(lo, mi-1);
}
int guessNumber(int n) {
return guessing(1, n);
}
Solution 2. Iteration.
int guessNumber(int n) {
int mi, re, hi = n, lo = 1;
while(true) {
mi = (hi - lo)/2 + lo;
re = guess(mi);
if(re == 0) return mi;
else if(re == 1) lo = mi + 1;
else hi = mi - 1;
}
}
172. Factorial Trailing Zeroes
https://leetcode.com/problems/factorial-trailing-zeroes/description/
Solution. The number of trailing 0 of n! equals the total number of factor 5 in 1, 2, ... , n.
Each step, n/5 is the number of integers that have at least one factor of 5 in 1,2,...,n.
int trailingZeroes(int n) {
if(n == 0) return 0;
int nz = 0;
while(n) {
nz += n/5;
n /= 5;
}
return nz;
}
Solution. The number of trailing 0 of n! equals the total number of factor 5 in 1, 2, ... , n.
Each step, n/5 is the number of integers that have at least one factor of 5 in 1,2,...,n.
int trailingZeroes(int n) {
if(n == 0) return 0;
int nz = 0;
while(n) {
nz += n/5;
n /= 5;
}
return nz;
}
Subscribe to:
Posts (Atom)