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

前端 未结 4 820
一整个雨季
一整个雨季 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:38

    You can't store them in a simple integer variable because in binary format

    00101 is same as 000101 which is same as 101 which only results into 5. The convertion between a decimal number and binary numbers don't consider leading zeroes so it is not possible to store leading zeroes with the same integer variable.

    You can print it but you can't store the leading zeroes unless you use array of ints...

    int num = 500;
    
    while(num > 0)
    {
        System.out.print(num%10);
        num = num/10;
    }
    

    Alternatively you can store the count of leading zeroes as a separate entity and combine them when ever you need to use. As shown below.

    int num = 12030;
    boolean leading=true;
    int leadingCounter = 0;
    int rev = 0;
    while(num > 0)
    {
        int r = num%10;
        if(r == 0 && leading == true)
            leadingCounter++;
        else
            leading = false;
        rev = rev*10 + r;
        num = num/10;
    }
    for(int i = 1; i <= leadingCounter ; i++)
        System.out.print("0");
    System.out.println(rev);
    

提交回复
热议问题