1.剑指offer:14-II题.剪绳子II
力扣https://leetcode.cn/problems/jian-sheng-zi-ii-lcof/
代码
class Solution {
public:
int cuttingRope(int n) {
if(n == 2) return 1;
if(n == 3) return 2;
long res = 1;
while(n > 4){
res *= 3;
res = res % 1000000007;
n -= 3;
}
return (int)(res * n % 1000000007);
}
};
2.剑指offer:43题.1~n整数中1出现的次数
力扣https://leetcode.cn/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/
代码
class Solution {
public:
int countDigitOne(int n) {
long long mulk = 1;
int ans = 0;
for(int k = 0; n >= mulk; ++k){
ans += (n / (mulk * 10)) * mulk + min(max(n % (mulk * 10) - mulk +1, 0LL), mulk);
mulk *= 10;
}
return ans;
}
};
3.剑指offer:44题.数字序列中某一位的数字
力扣https://leetcode.cn/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/
代码
class Solution {
public:
int findNthDigit(int n) {
int low = 1, high = 9;
while(low < high){
int mid = (high - low) / 2 + low;
if(totalDigits(mid) < n){
low = mid + 1;
}else{
high = mid;
}
}
int d = low;
int prevDigits = totalDigits(d-1);
int index = n - prevDigits - 1;
int start = (int)pow(10,d-1);
int num = start + index / d;
int digitIndex = index % d;
int digit = (num / (int)(pow(10,d-digitIndex-1))) % 10;
return digit;
}
int totalDigits(int length){
int digits = 0;
int curLength = 1, curCount = 9;
while(curLength <= length){
digits += curLength * curCount;
++curLength;
curCount *= 10;
}
return digits;
}
};
23.1.30 第三十一次
闲谈:
over。
最后,本文如有问题,欢迎指正。