How to put all zeros into an integer on the right without external storage

How can we shift all zeros to an integer to the right.

For example, int x = 560106 after offset x = 561600.

We cannot use another variable, and string manipulation is not a good answer.

Also, I know a dirty use method recursively depending on the integer length.

+3
source share
1 answer

I'm not sure if this is your solution, but a recursive implementation (sorry for using Scheme - I dabble in it, so I try to use it for practice):

(define (bubble-digit-up number digit)
  (if (= number 0)
      digit
    (let ((last-digit (modulo number 10)))
      (if (= last-digit 0)
          (* (bubble-digit-up (/ number 10) digit) 10)
        (+ (* number 10) digit)))))

(define (shift-zeros-right x)
  (if (<= x 0)
      0
    (let* ((last-digit (modulo x 10))
           (rest (shift-zeros-right (/ (- x last-digit) 10))))
      (bubble-digit-up rest last-digit))))

bubble-digit-up : . . , (bubble-digit-up 100 4) 1400. shift-zeros-right - , : , .

, , - ( ), , .


EDIT: let , :

(define (bubble-digit-up number digit)
  (if (= number 0)
      digit
    (if (= (modulo number 10) 0)
        (* (bubble-digit-up (/ number 10) digit) 10)
      (+ (* number 10) digit))))

(define (shift-zeros x)
  (if (<= x 0)
      0
    (bubble-digit-up 
     (shift-zeros (/ (- x (modulo x 10)) 10))
     (modulo x 10))))

EDIT2: Python :

def bubble_digit_up(num, digit):
    if num == 0:
        return digit
    else:
        if num%10 == 0:
            return 10*bubble_digit_up(num/10, digit)
        else:
            return 10*num + digit

def shift_zeros_right(x):
    if x <= 0:
        return 0
    else:
        return bubble_digit_up(shift_zeros_right(x/10), x%10)
+1

All Articles