[leetcode]Reverse Integer C语言

【题】
Reverse digits of an integer.

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

click to show spoilers.
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.
【题目分析】
这道题主要是对于溢出情况的处理。用long long类型的变量存放转换后的值。
【具体代码如下】

int reverse(int x) {
    if(x==0)return 0;
    int sign=1;
    int pox_x;
    if(x>0)pox_x=x;
    else 
    {   
        sign=-1;
        pox_x=-x;
    }
    int rev_x;
    if(x%10==0)return reverse(x/10);
    int number[10];
    int i=0;
    int digits=0;
    while(pox_x>0)
    {
        number[i]=pox_x%10;
        pox_x=pox_x/10;
        i++;
    }
    int j=0;
    long long count=0;
    while(j<i)
        {
            count=count*10+number[j];
            j++;
        }
        if(count>2147483647)return 0;
        else rev_x=count;
        return rev_x*sign;

}

【个人总结】
其实这道题我的解法是过于麻烦了。首先,对于x=1000这类情况,可以不用另外分情况讨论,递归的求解导致时间花费多。其次,当确定用 long long 类型后,不用新建一个number[10]数组,因为int型最大就是10位数,而long long 范围是 -9223372036854775808 ~ +9223372036854775807 ,它占用8个字节。所以这点上处理不恰当,啰嗦冗余。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目描述: 给定一个没有重复数字的序列,返回其所有可能的全排列。 示例: 输入: [1,2,3] 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] 解题思路: 这是一个典型的回溯算法的问题,我们可以通过递归的方式实现。我们先固定一个数,再递归求解剩下的数的排列,最后再将固定的数和递归求解的结果合并。 代码实现: void backtrack(int* nums, int numsSize, int** result, int* returnSize, int index) { if (index == numsSize) { // 递归结束 result[*returnSize] = (int *)malloc(numsSize * sizeof(int)); // 为result分配空间 memcpy(result[*returnSize], nums, numsSize * sizeof(int)); // 将nums复制到result中 (*returnSize)++; // 返回结果数量自增1 return; } for (int i = index; i < numsSize; i++) { // 遍历数组 // 交换元素 int temp = nums[index]; nums[index] = nums[i]; nums[i] = temp; // 递归 backtrack(nums, numsSize, result, returnSize, index + 1); // 恢复原数组 temp = nums[index]; nums[index] = nums[i]; nums[i] = temp; } } int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) { int count = 1; for (int i = 2; i <= numsSize; i++) { count *= i; // 计算排列的总数 } int** result = (int **)malloc(count * sizeof(int *)); *returnColumnSizes = (int *)malloc(count * sizeof(int)); *returnSize = 0; backtrack(nums, numsSize, result, returnSize, 0); for (int i = 0; i < *returnSize; i++) { (*returnColumnSizes)[i] = numsSize; } return result; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值