library(tidyverse)
library(readxl)
path <- "900-999/937/937 Number Equal to Sum of Digits.xlsx"
df <- read_excel(path, range = "A1:B13")
colnames(df) <- c("Number", "Expected")
smallest_digit_sum <- function(N) {
d <- max(2, ceiling(N / 9))
first <- N - 9 * (d - 1)
if (first <= 0) {
as.numeric(paste0("1", N - 1))
} else {
as.numeric(paste0(first, paste(rep("9", d - 1), collapse = "")))
}
}
result <- df |>
mutate(Result = map_dbl(Number, smallest_digit_sum))
all.equal(result$Result, result$Expected)
# [1] TRUEExcel BI - Excel Challenge 937

Challenge Description
🔰 Find the smallest number strictly greater than the input whose sum of all its individual digits is exactly equal to the input.
Solutions
Logic:
Work out how many digits are required if each digit can contribute at most
9.Fill the right side with as many
9s as possible.Compute the smallest leading digit that makes the total digit sum equal to
N.
Strengths:
Greedy and Direct:
- The answer is constructed mathematically rather than searched by brute force.
Compact Formula:
- The core idea is expressed in just a few lines.
Correct Handling of Small Inputs:
- The logic forces at least two digits so the result stays strictly greater than the input.
Areas for Improvement:
Readability of Edge Case:
- The
first <= 0branch needs a short explanation for first-time readers.
- The
Gem:
- Packing the tail with
9s and minimizing the leftmost digit is the elegant greedy insight.
- Packing the tail with
import math
import pandas as pd
path = "900-999/937/937 Number Equal to Sum of Digits.xlsx"
input_df = pd.read_excel(path, usecols="A", nrows=12)
test = pd.read_excel(path, usecols="B", nrows=12)
def smallest_digit_sum(N):
d = max(2, math.ceil(N / 9))
first = N - 9 * (d - 1)
if first <= 0:
return int("1" + str(N - 1))
else:
return int(str(first) + "9" * (d - 1))
result = input_df["Number"].apply(smallest_digit_sum)
print(result.equals(test["Answer Expected"]))
# TrueLogic:
Calculate the minimum digit count required.
Reserve the trailing digits for
9s.Build the smallest valid leading digit.
Join the digits into the final number.
Strengths:
No Brute Force:
- The construction is immediate and scalable.
Explicit Numeric Build:
- The code makes the greedy digit layout easy to inspect.
Symmetry with the R Solution:
- Both implementations express the same mathematical idea very clearly.
Areas for Improvement:
Commenting the Greedy Rule:
- A short note on why the
9s belong at the end would help readability.
- A short note on why the
Gem:
- The entire search space collapses into one direct digit-construction formula.
Difficulty Level
This task is moderate:
Requires a greedy numeric construction rather than trial and error.
Depends on recognizing how digit sums and place value interact.