Friday, August 18, 2017

LeetCode - 7. Reverse Integer

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; 

No comments:

Post a Comment

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 ...