题目描述
给你一个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
What's Going down i am new to this, I stumbled upon this I have found It positively useful and it has aided me out loads.
I hope to contribute & help different customers like
its helped me. Good job.
azithromycin in mexico
over the counter tretinoin
Because of these records becoming out there, genealogist and net builders use this tool to make a automated family tree, which makes it a straightforward to learn interface within the
web. With so lots of the records which can be crucial for any form of household tree search already saved in computer systems as we speak, start records, marriage data and death data you can get a head
begin on any sort of genealogy research. Analysis has shown that virtual avatars can affect body image
notion and will result in altered behaviors in the
true world. It's best to arrange some enjoyable activities that may engross the mind and develop
the colleges of the body.
Natural Food definitions amid the food products that are produced using environmental and animal pleasant farming methods in farms.
Though imported beef is on the market from other Latin American countries, Chileans prefer domestically
produced beef. These cake baking programs will enable you to
master it all. On the off probability that you simply order from a similar place often, the delivery professionals will get snug
with you. Why Free Food Residence Delivery Is considered As
a Handy Option? Yet with such an abundance of eating places, delivery kitchens,
and even food delivery apps, it isn't always simple
to choose the proper one. Be taught the precise method to make use of the
bakeware, oven and the measuring techniques.
There are so many suppliers who supply the objects which aren't fresh, because their only function is to
make cash. The single attachment hub makes it easy to use and there are a large variety
of non-compulsory equipment to assist you with different baking duties from mixing
cake batters to whipping cream. There can also be the role of
the state when it comes to those points typically dictating how
meals should be prepared. It is crucial to address mental well being points
as a part of an general method to healthcare.
Edible with out cooking, tsampa makes helpful trekking food.
So fill within the missing and buy some food supplements.
Moreover food trucks, cafes with themes is
another pattern we've been noticing rise since round 2015.
From cat cafes where cute felines run around while patrons sip coffee to e book/video recreation themed cafes like a Pokemon or a Harry
Potter Cafe, these themed cafes have been continuously popping up this 12 months!
Let's have a look. Nicely there you have got it, 6 powerful foods which are high
in antioxidants and are able to drastically decreasing
inflammation inside the physique. The lipids (fatty acids) in coconut oil
are robust anti-inflammatory compounds that lower inflammation inside the physique.
In idea, a large a part of brain cells may additionally operate by
exploiting fatty acids. A style for sweetness is part of human history.
Within the context of CBD, "introduction" refers back to the movement
by human agency, oblique or direct, of an alien species outdoors of its
natural range (previous or present). In keeping with a study published, it is alleged that cinnamaldehyde current in cinnamon stimulates the metabolism of the fatty visceral tissue, which can show to help lower stomach fat.
Ищете недорогой качественный диван, который долго прослужит? Добро пожаловать на официальный сайт интернет-магазина в раздел ! Здесь можно купить классические или угловые модели по доступной цене https://by-home.ru/kartiny-postery/13560-kartina-shinuazri-versiya-91-kholst-galerejnaya-natyazhka.html
Расцветки представлены благородными оттенками, как в сдержанных тонах, так и в ярких https://by-home.ru/nastennye-zerkala/26006-zerkalo-mone-vajt.html
Купить диван в Москве можно в пару кликов, выбрав самостоятельно или воспользовавшись помощью менеджера для подбора и оформления заказа https://by-home.ru/interernye-kresla/16346-kreslo-halmar-tyrion-seryjchernyj.html
Искренний сервис https://by-home.ru/101-chasy
Диваны и Кресла - официальный сайт интернет-магазина в Москве https://by-home.ru/barnye-i-polubarnye-stulya/24859-stul-barnyj-halmar-h101-chernyj.html
Популярные запросы https://by-home.ru/stulya/17291-komplekt-iz-4-kh-stulev-eames-bon-belyj.html
lasix 30 mg tablets
tretinoin cost
purchase modafinil online