题目描述
给你一个32位的有符号整数x,返回将x中的数字部分反转后的结果。
如果反转后整数超过32位的有符号整数的范围 [−2^31,2^31−1],就返回 0。
假设环境不允许存储64位整数(有符号或无符号)。
思路
1.数字反转
利用%和/,将x的最后一位数字提取出来,放到返回数字rev的最前面,由于是10进制整数,所以只要每次操作时*10进一位。
int digit = x % 10;// 提取最后一位数字
x /= 10;// x去除最后一位
rev = rev*10 + digit;// rev初始值为0,赋值给最终的数字
2.整数反转的范围限制
题目要求x是32位无符号整数,环境不允许存储64位整数
反转后整数超过32位的有符号整数的范围就返回0
官方思路
-2^31 <= rev * 10 + digit <= 2^31-1
不等式不成立则返回0
然后一堆花里胡哨数学操作ToT
推导成了
(-2^31)/10 <= rev <= (2^31-1)/10写的乱主要是不会传图,划掉
//最终代码,这里INT_MIN和INT_MAX应该是c语言中定义的int型的最大最小值
int reverse(int x) {
int rev = 0;
while (x != 0) {
if (rev < INT_MIN / 10 || rev > INT_MAX / 10) {
return 0;
}
int digit = x % 10;
x /= 10;
rev = rev * 10 + digit;
}
return rev;
}
我的理解
在数字转化的过程中,只要x不为0,rev就会比原来的值大10倍+,即rev = rev*10 + digit,所以为了避免超出范围,只要将rev和极值的1/10进行比较(在x!=0的前提下)。
假如还需要缩小范围,可以1、极值/100;2、条件改为while(x/10 !=0),不过该情况下对于x==0要单独考虑
今日总结
- 对于算法这方面还有很多需要加强的地方,主要在于做题的思路方面,需要多加练习。
- C、Java的基础方面还很薄弱,需要加强,多加练习
- 中等难度的题目就一头雾水了[o(╥﹏╥)o],我可真菜
本文由 szr 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Sep 14, 2021 at 04:46 pm
Портал Одеси https://faine-misto.od.ua/ — це інтернет-платформа для місцевих жителів, який публікує цікаві рекомендації про місцеві заходи. На платформі Файне Місто зможете ознайомитися актуальні новини про активності в Одесі.
Купить ски-пасс Красная Поляна сезон 2024-2025 по низкой цене от 1600 рублей в день
Where to play New Zealand casinos on roulette, or in online pokiez nz. Online casinos in New Zealand for money. The best casinos of all categories operating in the country.
He does not hear the slamming of the front door. Neither does he hear the footsteps on the wood floor in the hallway. The shower drowns away all this noise. I was surprised He wasn’t angry. He said,” boy you wait here, I am going to the bathroom.” He closed the door. He must sit on the toilet with pants down because I heard him losing the belt but didn’t hear him peeing. After a while, he called my name,” get in here ass sniffing slut.” I opened the door and crawled to the side of daddy. Daddy was still sitting on the toilet. . Just when I was confused why he sat that and did nothing. He stood up and pulled his pants up. I did take a peep of daddy’s huge uncut Middle Eastern dick. Half hard like 7inches already. While he was doing that, he grabbed my hair pushed right into the toilet, and closed the lid. “ smell my ass from there boy when it is still fresh.” He paused and continued, “ Don’t move.”
danatoto danatoto danatoto
Good day! I know this is kinda off topic however , I'd figured I'd ask.
Would you be interested in exchanging links or maybe guest authoring a blog post
or vice-versa? My blog covers a lot of the same subjects as yours and I feel we
could greatly benefit from each other. If you might be interested feel free to shoot me an e-mail.
I look forward to hearing from you! Superb blog by the way!
Прикольные анекдоты. История анекдотов.
He does not hear the slamming of the front door. Neither does he hear the footsteps on the wood floor in the hallway. The shower drowns away all this noise. porno dla dzieci “FUCK! FUCK!” He says, as he loosens the tightened grip on his fleshy-red-tool, while it throbs with its life-giving blood coursing through its many vein-filled region.
togelup togelup togelup
It's really a cool and useful piece of info.
I'm glad that you shared this useful info with us. Please stay
us informed like this. Thanks for sharing.
Портал https://u-misti.cherkasy.ua це інформаційний майданчик для усіх, хто цікавиться Черкасами, який збирає цікаві рекомендації про місцеві заходи. На інтернет-майданчику У місті Черкаси зможете ознайомитися огляди подій про місцеві новини.
Промокод – это комбинация символов, которую вводят в специально отведенную строку на сайте. После активации кода, пользователь получит вознаграждение от любимого БК. Обычно к промокоду прилагается подробное описание всех предлагаемых бонусов. Но иногда букмекеры позволяют игрокам выяснить назначение кода самостоятельно, ведь многие любят сюрпризы. В случае с промокодом, сюрприз наверняка окажется приятным, ведь его главная цель – создать игроку комфортные условия, заслужить лояльность. Существуют промокоды для новых игроков, которые действительны только при регистрации, и для постоянных – окно для ввода таких кодов находится под формой пополнения игрового баланса. Мелбет промокод при регистрации Введите: RS777 и тогда при депозите вы получите бонус 10400 рублей автоматически. Букмекерская контора Мелбет в 2024 году создала комфортные условия для заядлых беттеров и новых пользователей. Промокоды – вещь распространенная, потому найти их легко. Часто букмекеры размещают коды в свободном доступе, для всеобщего пользования. А промокоды для более значимых наград поступают игрокам индивидуально, например в качестве подарка ко дню рождения, извинения за возможные неудобства или просто в благодарность за сотрудничество.