Separate the Numbers

  • + 0 comments

    My answer in Typescript, accepted

    function separateNumbers(s: string): void {
        /**
         * idea is check each couple of number that can be starting number [num]
         * then check the [s] left that is the continues of [num]
         * 
         * + number [threshold]: amount of number of [num] we will take
         * + number [result]: final number we finded [num]
         */
    
        let threshold = 1
        let result = BigInt(0)
    
        // outer loop, get [num] by [threshold], increasing if [num] not beauty
        check_s: while (!result) {
            // [num] can't be large than haft of [s], mean [s] can't be beauty
            if (threshold > s.length / 2) break check_s;
    
            let num = BigInt(s.substring(0, threshold))
            let num_next = num + BigInt(1)
            let s_left = s.substring(threshold)
    
            // inner loop, keep reduce [s_left] till empty
            check_beauty: while (true) {
                if (s_left.startsWith(`${num_next}`)) {
                    s_left = s_left.replace(`${num_next}`, '')
                    num_next = num_next + BigInt(1)
                }
                // can't reduce, [s] is not beauty, break [check_beauty] inner loop
                else break check_beauty;
    
                // [s_left] empty, mean [num] is beauty, set [result = num], break [check_s] outer loop
                if (s_left.length == 0) result = num;
            }
    
            // inner loop check [num] is not beauty number, next
            threshold++;
        }
    
        // idk why console, why not return?
        console.log(result ? `YES ${result}` : 'NO')
    }