#3099
Easy Algorithms Harshad number
Math
83.4% acceptance
Feb 25, 2026
211
12
An integer divisible by the sum of its digits is said to be a Harshad number. You are given an integer x. Return the sum of the digits of x if x is a Harshad number, otherwise, return -1.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn sum_of_the_digits_of_harshad_number(x: i32) -> i32 {
let s: i32 = x.to_string().bytes().map(|b| (b - b'0') as i32).sum();
if x % s == 0 { s } else { -1 }
}
}