• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

土鳖不土,战斗力五

天地玄宗,万炁本根。广修万劫,证吾神通。
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode第七题

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

题意是反转十进制int并返回,需要注意的是,int表示范围为 -2147483648 ~ 2147483647,翻转之后的数值可能会溢出,而题意为:如果溢出则返回0。

 

 

long long int dmod(int n)
{
    long long int i = 1;
    while (n--)
        i *= 10;
    return i;
}

int reverse(int x) {
    int y = abs(x), bit, tmp = 0, len = 10, sign;
    long long int res = 0;
    if (x==0 || x==-2147483648) return 0;//int最小值取绝对值的话会溢出
    sign = x/y;
    while (len>1 && y / dmod(len-1) == 0)
    {
        len --;
    }
    for (bit=1; bit<=len; bit++)
    {
        tmp = y / dmod(bit-1) % 10;
        res += tmp * (dmod(len-bit));
    }
    //printf("sign = %d, res = %d\n", sign, res);
    if (res > 2147483647) return 0;
    return sign * (int)res;
}

 

posted on 2017-01-19 17:09  土鳖不土,战斗力五  阅读(215)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3