Source Link:
https://leetcode.com/problems/reverse-integer/description/
Question:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
My Solution:
Note:
1. using "long" (important)
long new_integer = 0;
2. processing the digits one by one (unitil old_integer ==0)
while(old_integer !=0)
3. take the tail (%10)
int tail = old_integer % 10;
4. add to new_integer (*10)
new_integer = new_integer * 10 + tail;
5. to next digit (/10)
old_integer = old_integer / 10;
6. checking "overflows" by Integer.MAX_VALUE and Integer.MIN_VALUE
if(new_integer > Integer.MAX_VALUE || new_integer < Integer.MIN_VALUE)
7. finally, from "long" back to "int"
return (int)new_integer;
Subscribe to:
Post Comments (Atom)
Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments
Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_distinct_slices/ Question: An integer M and a...
-
Source Link: https://app.codility.com/programmers/lessons/15-caterpillar_method/count_triangles/ Question: A zero-indexed array A consi...
-
Source Link: https://codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ Question: A non-empty zero-indexed array A...
No comments:
Post a Comment