LeetCode 2698: Find the Punishment Number of an Integer Solution
Master LeetCode problem 2698 (Find the Punishment Number of an Integer), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2698. Find the Punishment Number of an Integer
Problem Explanation
Explanation
To solve this problem, we iterate from 1 to n and for each i, we check if the square of i can be partitioned into contiguous substrings such that their sum equals i. If it satisfies the condition, we add i^2 to the punishment number. We can determine if a number can be partitioned by converting it to a string and checking all possible partitions of the string to sum up the integer values.
Time Complexity: O(n * m), where n is the input integer n and m is the number of digits in the square of n.
Space Complexity: O(m), where m is the number of digits in the square of n.
Solution Code
class Solution {
public int findPunishmentNumber(int n) {
int punishmentNumber = 0;
for (int i = 1; i <= n; i++) {
int square = i * i;
String squareStr = String.valueOf(square);
int sum = 0;
int j = 0;
while (j < squareStr.length()) {
String numStr = "";
while (j < squareStr.length() && Character.isDigit(squareStr.charAt(j))) {
numStr += squareStr.charAt(j);
j++;
}
if (!numStr.isEmpty()) {
sum += Integer.parseInt(numStr);
}
j++;
}
if (sum == i) {
punishmentNumber += square;
}
}
return punishmentNumber;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2698 (Find the Punishment Number of an Integer)?
This page provides optimized solutions for LeetCode problem 2698 (Find the Punishment Number of an Integer) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2698 (Find the Punishment Number of an Integer)?
The time complexity for LeetCode 2698 (Find the Punishment Number of an Integer) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2698 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2698 in Java, C++, or Python.