Understand Find the Punishment Number Problem

Problem Name: Find the Punishment Number
Problem Description:

Find the Punishment Number

Description

Given a positive integer ( n ), return its punishment number.

The punishment number of ( n ) is the sum of squares of all numbers ( i ) (where ( 1in1 \leq i \leq n )) that satisfy:

  • ( i2i^2 ) can be split into contiguous substrings,
  • The sum of these substrings equals ( i ).

Example 1

Input:

n = 12

Output:

182

Explanation: Numbers satisfying the condition:

  • ( 12=11^2 = 1 ) ✅
  • (92=818+1=99^2 = 81 \rightarrow 8 + 1 = 9) ✅
  • ( 102=10010+0=1010^2 = 100 \rightarrow 10 + 0 = 10 ) ✅

Total punishment number: ( 1 + 81 + 100 = 182 )


Example 2

Input:

n = 25

Output:

182

Explanation: Numbers satisfying the condition:

  • (12=1 1^2 = 1 ) ✅
  • (92=818+1=99^2 = 81 \rightarrow 8 + 1 = 9) ✅
  • (102=10010+0=10 10^2 = 100 \rightarrow 10 + 0 = 10 ) ✅

Total punishment number: ( 1 + 81 + 100 = 182 )


Constraints

1n10001 \leq n \leq 1000

Category:
  • Graphs
Programming Language:
  • Java
Reference Link:

https://leetcode.com/problems/find-the-punishment-number-of-an-integer/description/

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

Main Function is not defined.

Helper Function:

INPUT: n = 25

OUTPUT: 182

public static int punishmentNumber(int n) {

int sum = 0;

for (int i = 1; i <= n; i++) {

int square = i * i;

boolean condition_varibale = canPartition(String.valueOf(square), i, 0, 0);

if(condition_variable){

sum += square;

}//If End

}//Loop End

return sum;

} //function end

Utility Functions and Global variables:

private static boolean canPartition(String s, int target, int index, int currentSum) {

if (index == s.length()) {

return currentSum == target;

}//If End

int num = 0;

for (int i = index; i < s.length(); i++) {

num = num * 10 + (s.charAt(i) - '0');

int condition_variable = canPartition(s, target, i + 1, currentSum + num);

if(condtion_variable){

return true;

}//If End

}//Loop End

return false;

} //function end