Sorting digits of an integer

前端 未结 9 1278
日久生厌
日久生厌 2020-12-16 01:26

You are given an integer 51234 (say) we need to sort the digits of a number the output will be 12345.

How to do it without using array ?

9条回答
  •  盖世英雄少女心
    2020-12-16 01:57

    One could try something like an insertion sort. Essentially create a new number from taking one digit of the old one at a time and putting it in the correct place.something like this.

    while(num!=0){
    
    dig = num%10; // get the last digit 
    if(newNum=0 ) newNum+=dig;
    else{
        newNumTemp = 0; flag =1;i =1;
        while (newNum != 0){
        Newdig = newNum%10;
       if(flag){
          if (Newdig >= dig )
             {NewNumTemp = Newdig*(10^i)+ NewNumTemp; }
          else { flag=0; NewNumTemp = dig*(10^i) +NewNumTemp; i++;NewNumTemp = Newdig*   (10^i)+    NewNumTemp;}
    
         } // end of outer if 
         i++;
         newNum/=10;
    
       } // end of while
       newNum= newNumTemp;
    }// end of else 
    
    num/=10;
    
    }// end of outer while
    

提交回复
热议问题