714272. Powerfull Integer
Powerfull Integer
Slug: powerfull-integer--170647 Difficulty: Easy Id: 714272 Topic Tags: Hash, Sorting, Map, Data Structures, Algorithms Company Tags: None
Summary
Given a list of integers, find the most powerful integer in the list. The power of an integer is defined as the sum of its digits raised to their respective powers. For example, the power of 123 would be 1^3 + 2^2 + 3^1 = 28. The problem is to write a program that efficiently calculates the most powerful integer in the list.
Detailed Explanation
The solution involves iterating through each number in the list and calculating its power using a loop. We then store these powers in a hash map where the key is the original integer and the value is its calculated power. Finally, we iterate through the hash map to find the integer with the highest power.
Here's a step-by-step breakdown of the solution:
- Initialize an empty hash map
powers. - Iterate through each number in the list.
- For each number, calculate its power by summing the digits raised to their respective powers using a loop.
- Store the calculated power in the
powershash map where the key is the original integer and the value is its calculated power. - Initialize a variable
max_powerto store the maximum power found so far. - Iterate through the
powershash map to find the integer with the highest power. - Return the integer with the highest power.
Time complexity: O(n * k), where n is the number of integers in the list and k is the maximum digit value in an integer. Space complexity: O(n), for storing the powers in a hash map.
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public class PowerfullInteger {
public static int findMostPowerful(HashMap<Integer, Integer> numbers) {
int maxPower = 0;
int mostPowerful = -1;
for (Map.Entry<Integer, Integer> entry : numbers.entrySet()) {
int power = calculatePower(entry.getKey());
if (power > maxPower) {
maxPower = power;
mostPowerful = entry.getKey();
}
}
return mostPowerful;
}
private static int calculatePower(int number) {
int power = 0;
while (number > 0) {
int digit = number % 10;
power += Math.pow(digit, digit);
number /= 10;
}
return power;
}
}