7. 整数反转
转化为字符串
class Solution {
public:
void reverse_str(string& s, int l, int r) {
for (int i = l, j = r; i < j; i++, j--) swap(s[i], s[j]);
}
int reverse(int x) {
string s = to_string(x);
if (s[0] == '-') reverse_str(s, 1, s.size() - 1);
else reverse_str(s, 0, s.size() - 1);
long long t = stoll(s);
if (t > INT32_MAX || t < INT32_MIN) return 0;
else return t;
}
};
数学方法
因为不能使用long long所以上一个方法有点小问题
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
if (rev < INT_MIN / 10 || rev > INT_MAX / 10) {
return 0;
}
int digit = x % 10;
x /= 10;
rev = rev * 10 + digit;
}
return rev;
}
};
470. 用 Rand7() 实现 Rand10()
拆分十分之一为 二分之一乘五分之一
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution {
public:
int rand10() {
int a, b;
while ((a = rand7()) > 6); // 限定 a 的范围为 [1 - 6] 判断奇偶, 概率为二分之一
while ((b = rand7()) > 5); // 限定 b 的范围为 [1 - 5] 每个数的概率为五分之一
return (a & 1) == 1 ? 5 + b : b;
}
};
拒绝采样
7 * 7 拒绝大于40的数
class Solution {
public:
int rand10() {
int row, col, idx;
do {
row = rand7();
col = rand7();
idx = col + (row - 1) * 7;
} while (idx > 40);
return 1 + (idx - 1) % 10;
}
};