모듈러 계산 (역수 구하기)

ay.zip·2022년 4월 7일
0

TIL

목록 보기
26/47

input : 432
output: 234

input : -123
output : -321

class Solution {
public:
    int reverse(int x) {
    // 음수인지 아닌지를 구분하기 위함
        int flag = 1;
        if(x<=0){
            flag=-1;
        }
        
        //결과값 저장 공간
        int res=0;
        //절댓값으로 계산하기 쉽도록
        x=abs(x);
        
        while(x>0){
        예를 들어, 123%10 = 3
        12%10 = 2 
        1%10=1
            int temp=x%10;
            if(res>INT_MAX/10){
                return 0;
            }
            // 0*10+3 =3
            3*10+2=32
            32*10+1=321
            res=res*10+temp;
            123/10=12
            12/10=1
            x=x/10;
        }
        
        return res*flag;
    }
};

0개의 댓글

Powered by GraphCDN, the GraphQL CDN