c语言整数反转用while函数,7.整数反转(LeetCode)——C语言
根據(jù)題目要求,必須是32位有符號整數(shù),數(shù)值范圍是[-2^31, 2^31-1],換算出來就是-2147483648 —— 2147483647之間。將此范圍內(nèi)的數(shù)值反轉(zhuǎn)可能會(huì)導(dǎo)致溢出,比如1234567893,反轉(zhuǎn)之后為3987654321,已然超出了以上范圍。因此,先找出溢出條件,將其排除。
對一個(gè)整數(shù)x,x%10可以獲得x最后一位數(shù)字mod,也就是要獲得的反轉(zhuǎn)數(shù)值的首位數(shù)字。我們設(shè)reverse為反轉(zhuǎn)后的數(shù)值變量,則reverse = reverse * 10 + mod,reverse初始值設(shè)為0.當(dāng)reverse > 0時(shí):當(dāng)reverse > INT_MAX/10時(shí),reverse * 10 + mod必然溢出,此時(shí)應(yīng)返回0.
當(dāng)reverse == INT_MAX/10并且mod > 7時(shí),reverse * 10 + mod必然溢出,此時(shí)也返回0.
當(dāng)reverse < 0時(shí):當(dāng)reverse < INT_MAX/10時(shí),reverse * 10 + mod必然溢出,此時(shí)應(yīng)返回0.
當(dāng)reverse == INT_MAX/10并且mod < -8時(shí),reverse * 10 + mod必然溢出,此時(shí)也返回0.
循環(huán)對x%10取值,直到x為0時(shí),反轉(zhuǎn)已然完成,需要退出循環(huán),因此,循環(huán)進(jìn)行的條件為x != 0。#include
#include
int reverse(int x)
{
int mod = 0;
int reverse = 0;
while (x != 0)
{
mod = x % 10;
x = x / 10;
// 當(dāng)x為正值時(shí),reverse必是正值,則當(dāng)
// 當(dāng)reverse > INT_MAX/10時(shí),reverse*10 + mod 必然大于INT_MAX,必然溢出
// 當(dāng)reverse == INT_MAX/10時(shí),reverse*10 + mod要大于INT_MAX(即溢出),則mod必須大于7
if (reverse > INT_MAX / 10 || reverse == INT_MAX / 10 && mod > 7)
{
return 0;
}
// 同理,當(dāng)x為負(fù)值時(shí),reverse為負(fù)值,則當(dāng)
// reverse < INT_MIN / 10時(shí),reverse必然溢出
// reverse == INT_MIN / 10 && mod < -8,reverse溢出
if (reverse < INT_MIN / 10 || reverse == INT_MIN / 10 && mod < -8)
{
return 0;
}
reverse = reverse * 10 + mod;
}
return reverse;
}
int main (void) {
int x = 178237;
int y = -23682;
printf("%d %d %d %d", reverse(x), reverse(y), reverse(1234567894), reverse(-1234567894));
return 0;
}執(zhí)行用時(shí):4 ms, 在所有 C 提交中擊敗了66.25%的用戶
內(nèi)存消耗:5.6 MB, 在所有 C 提交中擊敗了34.16%的用戶
總結(jié)
以上是生活随笔為你收集整理的c语言整数反转用while函数,7.整数反转(LeetCode)——C语言的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bootstrap 日历中文_boots
- 下一篇: excel表格不够怎么添加_Excel表