In this HackerRank Sam and substrings problem solution, we have given an integer as a string, sum all of its substrings cast as integers. As the number may become large, return the value modulo 10 to power 9 plus 7.

HackerRank Sam and substrings problem solution


Problem solution in Python.

def solution(n):
    s = 0
    prev_sum = 0
    
    for i, d in enumerate(n):
        s_ = prev_sum * 10 + (i + 1) * int(d)
        s += s_
        prev_sum = s_
    return s % (10 ** 9 + 7)

n = input()

print(solution(n))

{"mode":"full","isActive":false}


Problem solution in Java.

import java.io.*;

public class Solution {
    
    private final static int MOD = 1000000007;
    
    public static void main(String[] args) throws IOException {
        
        int[] balls = strNumToArr((new BufferedReader(new InputStreamReader(System.in))).readLine());
        
        int n = balls.length;
        for(int i = n - 2; i >= 0; --i){
            balls[i] = (int)((balls[i+1] + (((long)balls[i])*(n - i))%MOD)%MOD);
        }
        
        int pow = 1;
        int total = 0;
        for(int i = 0; i < n; ++i){
            total = (int)((total + (((long)balls[i])*pow)%MOD)%MOD);
            pow = (int)((pow*10L)%MOD);
        }
        
        System.out.print(total);
    }
    
    private static int[] strNumToArr(String str){
        int n = str.length();
        int[] ar = new int[n];
        for(char c : str.toCharArray()){
            ar[--n] = c - '0';
        }
        return ar;
    }    
}

{"mode":"full","isActive":false}


Problem solution in C++.

#include <bits/stdc++.h>
using namespace std;
long long mod = 1000000007;

int main() {
    string s;
    cin >> s;
    long long pw[s.length() + 1];
    pw[0] = 1;
    for (int i = 1; i <= (int)s.length(); ++i) {
        pw[i] = pw[i - 1] * 10 % mod;
    }
    long long sum[s.length() + 1];
    sum[0] = pw[0];
    for (int i = 1; i <= (int)s.length(); ++i) {
        sum[i] = sum[i - 1] + pw[i];
        sum[i] %= mod;
    }
    long long ans = 0;
    int n = s.length();
    for (int i = 0; i < n; ++i) {
        ans += (s[i] - '0') * (i + 1) * sum[n - 1 - i];
        ans %= mod;
    }
    cout << ans << endl;
    return 0;
}

{"mode":"full","isActive":false}


Problem solution in C.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MOD 1000000007
#define MAX_SIZE 200000
int main() {

    unsigned long long one = 1;
    unsigned long long sum = 0;
    int len = 0;
    unsigned char input[MAX_SIZE];
    memset(input, 0, MAX_SIZE);
    scanf("%s", input);
    len = strlen(input);
    for(int i = len-1; i >= 0; i--)
    {
        sum = ( sum + (input[i] - '0') * (i + 1) * one ) % MOD;
        one = (one * 10 + 1) % MOD;
    }
    printf("%llu", sum);
}

{"mode":"full","isActive":false}