ABAP算法题:错位最接近数字问题

一个K位的数N
(K≤2000,N≤1020)
找出一个比N大且最接近的数,这个数的每位之和与N相同,用代码实现之。
例如:0050 所求书数字为0104;112 所求数为121;
算法分析 算法思想
直接暴力求这个数字是不可以的,数字的量级太大,有K位的数字,不可能直接用int,或者float来表示,使用数组来存储。应该分析这个数字,step1,从右边开始的最小位数开始,分解最后一位数字,分解出1来拿给前面的一位。9和0比较特殊,因此从左往右扫描的开始,遇到0就跳过,遇到第一个非0的数字,就把这个数字-1,然后移到最后面去,然后,step2,开始找第一个非9的数字,如果遇到9,就把9放到最后面去,遇到非9,就+1,结束运算。
一个般的例子:
1999000 -> 1990008-> 2000899
要注意一个问题,就是如果是 999000 这种情况,在数字的最开头补1,结果是1000899
几个刁蛮的数据:29399 -> 29489

以下为代码,应该有很大简化空间,但是懒的搞了

DATA a TYPE i.                                              "K≤2000

DATA:cnt TYPE i."一个无限累加的计数器
DATA str(5) TYPE c.
"input
DATA n TYPE p VALUE '29399' LENGTH 5.                        "N≤1020
DATA k TYPE i VALUE 5.                                      "K≤2000
"output
DATA x TYPE i.                                              "K≤2000

str = n.
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
  EXPORTING input  = str
  IMPORTING output = str.


DATA : off TYPE i, set TYPE i.

DATA:BEGIN OF wa_number,
       index  TYPE i,
       number TYPE i,
     END OF wa_number.
DATA it_number LIKE TABLE OF wa_number.

DO k TIMES.
  cnt = sy-index.
  off =  sy-index - 1.
  wa_number-index = sy-index.
  wa_number-number = str+off(1).
  APPEND wa_number TO it_number.
  CLEAR wa_number.
ENDDO.

SORT it_number  BY index DESCENDING.
cl_demo_output=>display( it_number ).

DO k TIMES.
  READ TABLE it_number INTO DATA(wa_tmp) INDEX sy-index.
  IF wa_tmp-number EQ 0.
  ELSE.
    IF sy-index eq 1.
      wa_tmp-number = wa_tmp-number - 1.
      MODIFY it_number FROM wa_tmp INDEX  sy-index.
    else.
      cnt += 1.
      wa_tmp-index = cnt.
      wa_tmp-number = wa_tmp-number - 1.
      MODIFY it_number FROM wa_tmp INDEX  sy-index.
    ENDIF.
    DATA(idx) =  sy-index + 1.
    PERFORM do_add USING idx.
    exit.
  ENDIF.
ENDDO.
*
CLEAR str..
SORT it_number  BY index.
LOOP AT it_number INTO wa_number..
  str = str && wa_number-number.
ENDLOOP.
cl_demo_output=>display( str ).

FORM do_add USING idx.

  SORT it_number  BY index DESCENDING.
  READ TABLE it_number INTO DATA(wa_tmp2) INDEX idx.
  IF sy-subrc EQ 0.
    IF wa_tmp2-number EQ 9.
      cnt = cnt + 1.
      DELETE it_number INDEX idx.
      wa_tmp2-index = cnt.
      APPEND wa_tmp2 TO it_number.
      DATA(idx2) = idx + 1.
      PERFORM do_add USING idx2.
    ELSE.
      wa_tmp2-number += 1.
      MODIFY it_number FROM wa_tmp2 INDEX idx.
    ENDIF.
  ELSE.
    wa_tmp-index = 0.
    wa_tmp-number = 1.
    APPEND wa_tmp2 TO it_number.
  ENDIF.

ENDFORM.

 

转载于:https://www.cnblogs.com/yibing-jia/p/11280779.html

你可能感兴趣的:(ABAP算法题:错位最接近数字问题)