Find the reverse of a number (ex : 2500 reverse 0025) without the help of string or character

前端 未结 4 812
一整个雨季
一整个雨季 2020-12-20 07:42

Is there any technique for finding the reverse when there are zeros at the end.

While following the algorithm of %10 technique the result is 52. And the 0\'s are mis

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 08:39

    Numbers are stored as binary 0 and 1 and so they always have leading 0's which are chopped off. e.g. a 64-bit integer has 64-bit bits, always and when it is printed these leading 0's are dropped.

    You need to know how many leading zeros you want to keep and only use that many when you print. i.e. you can record how many leading zeros there were in a normal number without encoding it e.g. by adding a 1 at the start. i.e. 0052 is recorded as 10052 and you skip the first digit when you print.

    If you need to store a single value you can do the following. I use do/while so that 0 becomes 10 and is printed as 0. The number 0 is the one place where not all leading zeros are dropped (as it would be empty otherwise)


    This appears to be the solution you want and it should be basically the same in C or C++

    static long reverse(long num) {
        long rev = 1; // the 1 marks the start of the number.
        do {
            rev = rev * 10 + num % 10;
            num /= 10;
        } while(num != 0);
        return rev;
    }
    
    // make the reversed number printable.
    static String toStringReversed(long num) {
        return Long.toString(num).substring(1);
    }
    
    long l = reverse(2500); // l = 10052
    

    An alternative is to print the digits as you go and thus not need to store it.

    e.g.

    static void printReverse(long l) {
        do {
            System.out.print(l % 10);
            l /= 10;
        } while(l != 0);
    }
    

    or you can have the input record the number of digits.

    static void printReverse(long l, int digits) {
        for(int i = 0; i < digits; i++) {
            System.out.print(l % 10);
            l /= 10;
        }
    }
    
    // prints leading zero backwards as well
    printReverse(2500, 6); // original number is 002500
    

    prints

    005200
    

提交回复
热议问题