Created
April 5, 2021 19:27
-
-
Save pokrakam/fc0bc3623a97bbfe71e33a7d1918511b to your computer and use it in GitHub Desktop.
Answer to coding puzzle on Narcissistic Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
REPORT znarcissistic_numbers. | |
" https://blogs.sap.com/2021/03/20/another-abap-puzzle-narcissistic-numbers/ | |
PARAMETERS p_digits TYPE i DEFAULT 5. | |
CLASS lcl_narcissist DEFINITION CREATE PUBLIC. | |
PUBLIC SECTION. | |
METHODS run IMPORTING i_length TYPE i. | |
PRIVATE SECTION. | |
DATA power TYPE i VALUE 1. | |
METHODS check IMPORTING i_number TYPE i | |
i_sum_of_powers TYPE i | |
i_pos TYPE i. | |
ENDCLASS. | |
CLASS lcl_narcissist IMPLEMENTATION. | |
METHOD run. | |
check( i_number = 0 | |
i_sum_of_powers = 0 | |
i_pos = i_length ). | |
ENDMETHOD. | |
METHOD check. | |
CHECK i_sum_of_powers <= i_number. "Performance | |
DO 10 TIMES. | |
DATA(digit) = sy-index - 1. | |
IF i_pos > 1. | |
check( i_number = i_number + digit * 10 ** ( i_pos - 1 ) | |
i_sum_of_powers = i_sum_of_powers + digit ** power | |
i_pos = i_pos - 1 ). | |
IF power < i_pos. | |
power = i_pos. | |
ENDIF. | |
ELSE. | |
IF i_number + digit = i_sum_of_powers + digit ** power. | |
WRITE |{ i_number + digit } |. | |
ENDIF. | |
ENDIF. | |
ENDDO. | |
ENDMETHOD. | |
ENDCLASS. | |
START-OF-SELECTION. | |
NEW lcl_narcissist( )->run( p_digits ). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Deliberate strategy to use recursion and (mostly) immutable data.