algorithm to find a number in which product of number of 4 & 7 is maximum in given range

后端 未结 2 1590
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 14:25

I am stuck in a question in which lower bound L and Upper bound U is given.
Now suppose in the decimal representation of integer X

相关标签:
2条回答
  • 2021-01-06 14:57

    If I understood the problem correctly, the following should work:

    • Assume all numbers have the same number of digits (if e.g. L has less digits than U, we can just fill in the beginning with 0 s).
    • Let Z = U - L.
    • Now we go from the first (/highest/leftmost) digit to the last one. If we are looking at the i th digit, let L(i), U(i), Z(i) and X(i) be the corresponding digit.
      • for all leading Z(i) which are 0, we set X(i) = L(i) (we don't have a choice).
      • For the first not 0 Z(i) check: is there a 4 or a 7 in the interval [L(i), U(i)-1]? If yes let X(i) be that 4 or 7 otherwise let X(i) = U(i)-1.
      • Now fill up the rest of X with 4s and 7s such that you choose a 4 if you have assigned more 7s so far and vice versa.

    Maybe an example can help in understanding this:

    Given U = 5000 and L = 4900.

    Now Z = 0100.

    From the algorithm we set

    • X(1) = L(1) = 4 (we have no choice)
    • X(2) = U(2)-1 = 9 (the first non 0 digit in Z)
    • X(3) = 7 (we already had a 4)
    • X(4) = 4 (can be chosen arbitrarily)

    Leading to X = 4974 with an objective of 2*1=2

    0 讨论(0)
  • 2021-01-06 15:20

    It seems you have the algorithm thought out already. Just break it down piece by piece and solve each part. I usually write something like you did there with comments and then break those down until they are at a reasonable bite size to write code for.

    When you have it working, if needed, you can optimize it.

    0 讨论(0)
提交回复
热议问题