剑指 Offer 14- II. 剪绳子 II
将数字分成若干个三的时候乘积最大
class Solution {
public:
int cuttingRope(int n) {
long long ans=1;
if(n==2) return 1;
if(n==3) return 2;
while(n){
if(n>=3){
if(n==4){
ans*=n;
ans%=1000000007;
n-=4;
break;
}
else{
ans*=3;
ans%=1000000007;
}
}
else{
ans*=n;
ans%=1000000007;
}
n-=3;
if(n<=0) break;
}
return (int)ans%10000000007;
}
};
通过计算从1到n的过程中每一位上有多少次是1来计算总和
class Solution {
public:
int countDigitOne(int n) {
long long digit = 1, res = 0;
long long high = n / 10, cur = n % 10, low = 0;
while(high != 0 || cur != 0) {
if(cur == 0) res += high * digit;
else if(cur == 1) res += high * digit + low + 1;
else res += (high + 1) * digit;
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return res;
}
};
剑指 Offer 44. 数字序列中某一位的数字
从后往前推每一位对应的数值,减去当前的数,最后将n所在的数字的位数算出来,然后取模求指定数字
class Solution {
public:
int findNthDigit(int n) {
n -= 1;
for (long digits=1;digits < 11;++digits ){
int first_num = pow(10,digits-1);
if (n < 9 * first_num * digits){
return int(to_string(first_num + n/digits)[n%digits])-'0';
}
n -= 9 * first_num * digits;
}
return 0;
}
};