Sam and substrings Discussions | Algorithms | HackerRank

Sort by

recency

|

213 Discussions

|

  • + 0 comments

    Sam and Substrings

  • + 0 comments

    Solution in Python3:

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    #
    # Complete the 'substrings' function below.
    #
    # The function is expected to return an INTEGER.
    # The function accepts STRING n as parameter.
    #
    
    def substrings(n):
        # Write your code here
        modulo = int(1e9 + 7)
        result = sub_sum = int(n[0])
    
        for digit_idx in range(1, len(n)):
            digit = int(n[digit_idx])
            digit_presence = digit_idx + 1
            sub_sum = (sub_sum * 10 + digit * digit_presence) % modulo
            result = (result + sub_sum) % modulo
    
        return result
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        n = input()
    
        result = substrings(n)
    
        fptr.write(str(result) + '\n')
    
        fptr.close()
    
  • + 0 comments

    JAVA SOLUTION

     private final static BigInteger MOD = BigInteger.valueOf(1000000007);
    
        /*
         * Input: 123456 
         * Role of '2': 2, 20, 200, 2000, 20000, 200000
         */
        public static int substrings(String number) {
            int length = number.length();
            BigInteger totalSum = BigInteger.valueOf(0);
            BigInteger multiplier = BigInteger.valueOf(1);
            BigInteger sum = BigInteger.valueOf(0);
    
            // Iterate over each digit from the end to the start
            for (int i = length - 1; i >= 0; i--) {
                BigInteger digit = BigInteger.valueOf(Character.getNumericValue(number.charAt(i)));
                sum = (sum.add(digit.multiply(multiplier))).mod(MOD);
                totalSum = (totalSum.add(sum)).mod(MOD);
                multiplier = (multiplier.multiply(BigInteger.valueOf(10)).add(BigInteger.valueOf(1))).mod(MOD);
            }
    
            return totalSum.intValue();
        }
    
  • + 0 comments

    My code: def substrings(n): arr=[int(x) for x in n] _sum=0 for i in range(len(arr)): print(arr[i]) for k in range(len(arr)-i, 0, -1): _sum+=_mod(arr[i]10*(k-1)*(i+1)) return _mod(_sum)

  • + 1 comment

    What are the substrings of 1111?