Facebook Interview Question
Software Engineer InternsCountry: United States
Interview Type: Phone Interview
public static void FindNarcisisitcNumbers() {
int n = 3;
List<Integer> nums = new ArrayList<Integer>();
nums.add(0);
int power = 1;
for (int i = 1; i <= n; i++) {
for (int j = power; j < power * 10 ; j++) {
int temp = j;
int sum = 0;
while (temp != 0) {
sum += Math.pow(temp % 10, i);
temp /= 10;
}
if (sum == j)
nums.add(j);
}
power *= 10;
}
for (int nu : nums)
System.out.println(nu);
}
Result:
0
1
2
3
4
5
6
7
8
9
153
370
371
407
Hope this helps
public static void main(String[] args) {
System.out.print("Enter the limit : ");
int n = (new Scanner(System.in)).nextInt();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i == findSOC(i)) {
list.add(i);
}
}
System.out.println(list);
}
private static int findSOC(int i) {
if (i == 0)
return 0;
return findSOC(i / 10) + cube(i % 10);
}
private static int cube(int i) {
return i * i * i;
}
func cubeAllDigits(in number:Int) -> Int {
var sum = 0
var left = number
while left > 0 {
let x = left % 10
sum += x * x * x
left = (left - x) / 10
}
return sum
}
print(cubeAllDigits(in: 2)) // 8
print(cubeAllDigits(in: 153)) // 153
print(cubeAllDigits(in: 103)) // 28
print(cubeAllDigits(in: 555555)) // 750
{ static void Main(string[] args)
{
double res;
for (int i = 1; i < 10; i++)
{
for (int j = 1; j < 10; j++)
{
for (int k = 1; k < 10; k++)
{
res = Math.Pow(i, 3) + Math.Pow(j, 3) + Math.Pow(k, 3);
if ( res == int.Parse(i.ToString() + j.ToString() + k.ToString()) )
{
Console.WriteLine(res);
}
}
}
}
Console.ReadLine();
}}
Some explanations in the comment to implementation.
I didn't find similar solutions in the example from above, so, I've decided to add my own.
- Mike L March 02, 2019