1. 程式人生 > >LeetCode 7 反轉整數 (Reverse Integer) —— 得到整形數的位數及尾數

LeetCode 7 反轉整數 (Reverse Integer) —— 得到整形數的位數及尾數

這裡使用一種較笨的方法,適合初學者理解。

主要的過程就是用取餘操作得到最後一位,用除法操作得到一共有幾位。具體程式如下:

// An highlighted block
class Solution {
public:
    int reverse(int x) {
        //取相反數
        int n = 0;
        long sum = 0;
        int pos;
        if(x<0)
            pos = -x;
        else
            pos = x;
            
        //得到位數和餘數        
vector<int> y (32,0); for(int i = 0; pos!= 0; ++i ) { n++; y[i] = pos%10; pos /= 10; } //得到新數 for(int j = 0; j < n; j++ ) { sum *= 10; sum = sum + y[j]; } //去不去掉0
if(sum%10 == 0) sum /= 10; //加不加負號 if(x<0) sum = -sum; //排除特殊 if(sum>=2147483648||sum<-2147483648) return 0; return sum; } };