Allen M - 7 days ago 4x

Ruby Question

Angstrom number example: 153;

`1**3 + 5**3 + 3**3 = 153`

`puts "Enter a number: "`

number = gets.chomp.to_i

initial_number = number

angstrom = 0

while (number % 10) != 0

number = number % 10

angstrom = angstrom + (number ** 3)

number = number / 10

end

puts angstrom

puts initial_number

if angstrom == initial_number

puts "YES ANGSTROM"

else

puts "NO ANGSTROM"

end

EX: Input is 123

Entering while, we get 12 after the number % 10 statement. But, after that, it doesn't go into while again; why is that?

`12 % 10`

`0`

I added the

`puts angstrom`

`puts initial_number`

Answer

I suspect you want something more along the lines of:

```
angstrom = 0
while number > 0
digit = number % 10
angstrom += digit ** 3
number /= 10
end
```

to isolate each digit without destroying the number, and to avoid early termination from zeros contained internally in the input number.

Source (Stackoverflow)

Comments