[Hacker Rank] Sam and substrings

Sam and substrings

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
int substrings(string n) {
long long mod = 1e9 + 7;
long long res = 0;
long long sum = 0;
for(long long i = 0; i < n.length(); i++) {
sum = sum * 10 % mod + (i + 1) * (n[i] - '0') % mod;
sum %= mod;
res = (res + sum) % mod;
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/13/PS/HackerRank/sam-and-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.