---
# System prepended metadata

title: \#7 Reverse Integer
tags: [leetcode, leetcode-easy]

---

# \#7 Reverse Integer
## *反轉自然數*
## Log
 - build 20210328 by syhuang

## 一般解
 - 兩變數a,b分別存給的值和轉換後的值, 用迴圈跑b=a%10+b, 每跑一次迴圈後a=a\10, b=b*10, 跑到a%10=0為止
```javascript=
var reverse = function(x) {
    var token = x>=0?1:-1;
    var tmp = Math.abs(x);//未算完數
    var ret = 0;
    do{
        ret = ret*10 + tmp%10;
        tmp = parseInt(tmp/10);
    }while(tmp > 0);
    ret = ret*token;
    if(ret >= Math.pow(2,31) || ret < -Math.pow(2,31)){return 0;}
    return ret;
};
```
## 初見(FUN)
 - 數字轉字串後反轉字串, 剛好javascript有字串反轉方法可用
```javascript=
var reverse = function(x) {
    var token = '';
    var a = x.toString();
    if(a[0]==='-'){token='-';a = a.substr(1);}
    var b = a.split('');
    var c = b.reverse();
    var d = c.toString();
    while(d.indexOf(',')>-1){
        d = d.replace(',','');
    }
    d = Number(token+d);
    if(d < -Math.pow(2,31) || d >= Math.pow(2,31)){d = 0;}
    return d;
}
```
## 備註
## 參考
###### tags: `leetcode`, `leetcode-easy`