How to deal with a summing digits method - java

I built 2 methods 1 get a number's digits, the 2nd sums all the digits of the number. It works , but for some reason when i type the number 11111 or higher it returns a wrong result.
For ex. the number 11111 returns 3 instead of 5
public class test_2 {
public static int getDigits(int x) {
int counter = 0;
while (x > 0) {
x /= 10;
counter++;
}
return counter;
}
public static int getNumber(int y) {
int New = 0;
for (int i = 0; i <= test_2.getDigits(y); i++) {
New += (y % 10);
y /= 10;
if (y < 10 && y > 0)
New += (y % 10);
}
return New;
}
}

There are multiple issues with your code, Follow below
test_2.getDigits(y) changes in each iteration of the loop, since y keeps changing
if (y < 10 && y > 0) condition is not necessary
The following will work:
public static int getNumber(int y) {
int New = 0;
for (int i = 0, len = getDigits(y); i < len; i++) {
New += (y % 10);
y /= 10;
}
return New;
}
Or simply:
public static int getNumber(int y) {
int New = 0;
while (y > 0) {
New += (y % 10);
y /= 10;
}
return New;
}

Related

How to convert tail-recursive function to iterative

How can you convert the following function so that it is iterative?
public static int recursion(int x, int y) {
if(x <= 0) {
return y + 13;
} else if (x == 1) {
return y;
} else {
return y * recursion(x - 2, y);
}
}
TL;DR Final code:
public static int iterative(int x, int y) {
int result = 1;
if(x <= 0) return y + 13;
for(; x >= 0; x -= 2)
result *= (x <= 0) ? y + 13 : y;
return result;
}
The technique in your case is to turn the recursive call into a loop:
while(true){
}
let us look at the recursive call y * recursion(x - 2, y); there is a multiplication and only x changes, so we need to create a variable to keep track of the multiplication:
int result = 1;
while(true){
//...
result *= y;
x = x - 2;
}
We initialized to 1 because it is a multiplication. Let us look at the cases where the recursive call stops:
if(x <= 0) {
return y + 13;
} else if (x == 1) {
return y;
let us add them into loop:
int result = 1;
while(true){
if(x <= 0) {
result *= y + 13;
break;
}
else if (x == 1){
result *= y;
break;
}
result *= y;
x = x - 2;
}
Now let us simplify the code, result *= y; shows two times, we can change the loop into:
while(true){
if(x <= 0) {
result *= y + 13;
break;
}
result *= y;
if (x == 1){
break;
}
x = x - 2;
}
Since the value of x does not matter outside the loop we can simplify the loop even further:
do{
if(x <= 0) {
result *= y + 13;
}
else
result *= y;
x = x - 2;
}while(x >= 0);
Let us use the ternary operator:
do{
result *= (x <= 0) ? y + 13 : y;
x = x - 2;
}while(x >= 0);
Let us use a for loop instead :
public static int iterative(int x, int y) {
int result = 1;
for(; x >= 0; x -= 2)
result *= (x <= 0) ? y + 13 : y;
return result;
}
We need to cover the case when the method is called with x <= 0:
public static int iterative(int x, int y) {
if(x <= 0) return y + 13;
int result = 1;
for(; x >= 0; x -= 2)
result *= (x <= 0) ? y + 13 : y;
return result;
}
public static int recursion(int x, int y) {
int result = 1;
while(true) {
if (x <= 0) {
result *= (y + 13);
break;
} else if(x == 1) {
result *= y;
break;
} else {
result *= y;
x -= 2;
}
}
return result;
}
public static int recursion(int x, int y) {
for(x;x>=1;x-=2){
y = y*y;
if(x==1) break;
}
if(x<=0){
return y*(y + 13);
}else if(x==1){
return y*y;
}
}
Make lists where the needed variables are stored.
One possible way would be to have two loops:
In the first loop you simulate the recursive calls, and
in the second loop you then process the formula around those calls, namely y*list[i] (pseudocode).
Tests: Keep your recursive function, and write a test that calls both and compares results, to verify/validate your non-recursive algorithm.

What is wrong with my java code for Project Euler's program 4? (finding the largest palindrome of 2 3 digit numbers)

This is my code and the answer always seems to 100001 (its not even
performing the loop).
I know there are much easier ways to solve this problem but what exactly is wrong with this particular code? and how do I fix it?
public class LargestPalindromes
{
public static void main(String[] args)
{
int largest = 100001;
for(int i = 100; i < 1000; i++)
{
for(int j = 100; j < 1000; j++)
{
int mult = i * j;
if(largest < mult && isPalindrome(mult))
largest = mult;
}
}
System.out.printf("\n\nThe largest palindrome is: %d\n\n", largest);
}
public static boolean isPalindrome(int mult)
{
int n1=0, n2=0, n3=0, n4=0, n5=0, n6=0;
int largest = 0, count = 0, p =100000;
int x = mult;
while(count < 6)
{
if(count == 1)
n1 = x / p;
else if(count == 2)
n2 = x / p;
else if(count == 3)
n3 = x / p;
else if(count == 4)
n4 = x / p;
else if(count == 5)
n5 = x / p;
else if(count == 6)
n6 = x / p;
x %= p;
p /= 10;
count++;
}
int reverse = Integer.valueOf(String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5) + String.valueOf(n6));
return reverse == mult;
}
}
There were too many errors in your original public static boolean isPalindrome(int mult) method. So I replaced it with the standard version:
public static boolean isPalindrome(int mult)
{
int temp=mult;
int r,sum=0;
while(mult>0){
r=mult%10; //getting remainder
sum=(sum*10)+r;
mult=mult/10;
}
if(temp==sum)
return true;
else{
return false;
}
}

Way to get number of digits from a long using Modulos

My ta told me that if i want to count the length of a long variable I can create a method using modulos. From what I understood he was saying that i need to keep using modulos until the long is 0. Here's what I'm thinking right now, but i'm pretty lost.
public static int inputSize(long cc_num)
{
int count = 0;
while( cc_num > 0)
{
count += 1;
cc_num = cc_num % 10;
}
}
That's almost correct.
Just replace the % operator with / operator:
cc_num /= 10;
That should work :)
Here is your code with minor changes:
public static boolean validSize(long cc_num) {
int count = 0;
if (cc_num < 0) cc_num *= -1; // fix negative number
while (cc_num > 0) {
count++;
cc_num = cc_num / 10;
}
//checks if length of long is correct
return count == 15 || count == 16;
}
Let me know if this works for you.
If you want to limit the number of possible comparisons:
public static int inputSize(long cc_num)
{
if(cc_num < 0) // check for negative numbers
cc_num = -cc_num;
int count = 1;
if(cc_num >= 10000000000000000L)
{
count += 16;
cc_num /= 10000000000000000L;
}
if(cc_num >= 100000000)
{
count += 8;
cc_num /= 100000000;
}
if(cc_num >= 10000)
{
count += 4;
cc_num /= 10000;
}
if(cc_num >= 100)
{
count += 2;
cc_num /= 100;
}
if(cc_num >= 10)
{
count ++;
}
return count;
}

Trying to wrap my head around 3 nested if statments

Say I have an array of 5 strings and that related to that array is 3 arrays of integers all of the same size. e.g.`
String a[] = new String[5]
int x[] = new int[5]
int y[] = new int[5]
int z[] = new int[5]
so that a[0],x[0],y[0],z[0] are all related to the same thing.
I want to find out which index(es) in x[] hold the highest number. If more than one those has the same highest number then which of those has the highest number in y[] and if there is more than one with the same highest number which one would have the highest in z[](Its safe to assume that none would have the same max value in z[]
I've tried to explain as best I can..
This is the best if got it only checks the first 2 conditions
for(int i=0;i<a.length;i++)
{
if(x[i]>=maximum){
if(x[i]==maximum)
{
if(y[i]>=maximum)
{
maximum=x[i];
winner=a[i];
maximum=y[i];
}
}
else
{
maximum=x[i];
winner=teams[i];
maximum=y[i];
}
}
So this is my new code
static int compareValues(){
for (int i=0; i<a.length; i++){
int max =0;
int diff = x[i] - x[max];
if (diff == 0){
diff = y[i] - y[max];
}
if (diff == 0){
diff = z[i] - z[max];
}
if (diff > 0){
max = i
}
}
return max;
}
If the String[n] is related to the int[n]s for each n then really you should compose them properly, make them Comparable and sort them.
class Thing implements Comparable<Thing> {
final String a;
final int x;
final int y;
final int z;
public Thing(String a, int x, int y, int z) {
this.a = a;
this.x = x;
this.y = y;
this.z = z;
}
#Override
public int compareTo(Thing o) {
int diff = o.x - x;
if (diff == 0) {
diff = o.y - y;
}
if (diff == 0) {
diff = o.z - z;
}
return diff;
}
#Override
public String toString() {
return "{" + a + "," + x + "," + y + "," + z + "}";
}
}
public static int max(Thing[] things) {
// NB - This should really call compareTo.
int max = 0;
for (int i = 1; i < things.length; i++) {
int diff = things[i].x - things[max].x;
if (diff == 0) {
diff = things[i].y - things[max].y;
}
if (diff == 0) {
diff = things[i].z - things[max].z;
}
if (diff > 0) {
// Higher
max = i;
}
}
return max;
}
public void test() {
Thing[] things = new Thing[6];
things[0] = new Thing("Hello", 1, 2, 3);
things[1] = new Thing("There", 1, 2, 4);
things[2] = new Thing("Everyone", 0, 2, 3);
things[3] = new Thing("How", 9, 0, 3);
things[4] = new Thing("Are", 8, 9, 3);
things[5] = new Thing("You", 7, 2, 3);
System.out.println("Before: " + Arrays.toString(things));
System.out.println("Max: " + things[max(things)]);
Arrays.sort(things);
System.out.println("Sorted: " + Arrays.toString(things));
}
This solution might be easier to understand:
static String compareValues() {
// find the maximum in x
int xMax = Integer.MIN_VALUE;
for (int i = 0; i < 5; i++) {
if (x[i] > xMax) {
xMax = x[i];
}
}
// find the maximum in y, but limited to the positions where x is maximal according to the calculation above
int yMax = Integer.MIN_VALUE;
for (int i = 0; i < 5; i++) {
if (x[i] == xMax && y[i] > yMax) {
yMax = y[i];
}
}
// find the maximum in z, but limited to the positions where y is maximal according to the calculation above
int zMax = Integer.MIN_VALUE;
int iMax = 0;
for (int i = 0; i < 5; i++) {
if (y[i] == yMax && z[i] > zMax) {
zMax = z[i];
iMax = i; // record the maximum position
}
}
return a[iMax];
}
I did not test the code, but I think that it should work.

Reverse Integer leetcode -- how to handle overflow

The problem is:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
The solution from the website I search is:
public class Solution {
public static int reverse(int x) {
int ret = 0;
boolean zero = false;
while (!zero) {
ret = ret * 10 + (x % 10);
x /= 10;
if(x == 0){
zero = true;
}
}
return ret;
}
public static void main(String[] args) {
int s = 1000000003;
System.out.println(reverse(s));
}
}
However when s = 1000000003, the console prints -1294967295 instead of 3000000001. So this solution still does not solve the overflow problem if we cannot use exception. Any help here?(Although there is a hint: add an extra parameter, I still cannot figure out what parameter I should add)
There's no need for any data type other than int.
Just make sure when there's an operation that increases a number, reversing the operation should give you the previous number. Otherwise, there's overflow.
public int reverse(int x) {
int y = 0;
while(x != 0) {
int yy = y*10 + x%10;
if ((yy - x%10)/10 != y) return 0;
else y = yy;
x = x/10;
}
return y;
}
Above most of the answers having a trivial problem is that the int variable possibly might overflow. You can try this : x = -2147483648 as parameter.
There has an easy way to solve the problem. Convert x to long, and check if the result >= Integer.MAX_VALUE, otherwise return 0.
The solution passed all test cases on https://leetcode.com/problems/reverse-integer/
This is a java version.
public int reverse(int x) {
long k = x;
boolean isNegtive = false;
if(k < 0){
k = 0 - k;
isNegtive = true;
}
long result = 0;
while(k != 0){
result *= 10;
result += k % 10;
k /= 10;
}
if(result > Integer.MAX_VALUE) return 0;
return isNegtive ? 0 - ((int)result) : (int)result;
}
C# version
public int Reverse(int x)
{
long value = 0;
bool negative = x < 0;
long y = x;
y = Math.Abs(y);
while (y > 0)
{
value *= 10;
value += y % 10;
y /= 10;
}
if(value > int.MaxValue)
{
return int.MaxValue;
}
int ret = (int)value;
if (negative)
{
return 0 - ret;
}
else
{
return ret;
}
}
Python version
def reverse(self, x):
isNegative = x < 0
ret = 0
x = abs(x)
while x > 0:
ret *= 10
ret += x % 10
x /= 10
if ret > 1<<31:
return 0
if isNegative:
return 0 - ret
else:
return ret
This java code handles the overflow condition:
public int reverse(int x) {
long reverse = 0;
while( x != 0 ) {
reverse = reverse * 10 + x % 10;
x = x/10;
}
if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) {
return 0;
} else {
return (int) reverse;
}
}
This is an old question, but anyway let me have a go at it too! I just solved it on leetcode. With this check, you never hit the overflow/ underflow in either direction, and I think the code is more concise than all the listed codes. It passes all test cases.
public int reverse(int x) {
int y = 0;
while(x != 0) {
if(y > Integer.MAX_VALUE/10 || y < Integer.MIN_VALUE/10) return 0;
y *= 10;
y += x % 10;
x /= 10;
}
return y;
}
you can try this code using strings in java
class Solution {
public int reverse(int x) {
int n = Math.abs(x);
String num = Integer.toString(n);
StringBuilder sb = new StringBuilder(num);
sb.reverse();
String sb1;
sb1 = sb.toString();
int foo;
try {
foo = Integer.parseInt(sb1);
}
catch (NumberFormatException e){
foo = 0;
}
if(x < 0){
foo *= -1;
}
return foo;
}
}
My soluton for this problem is to convert integer inputed to c-string, then everthing will be easy.
class Solution {
public:
int reverse(int x) {
char str[11];
bool isNegative = false;
int i;
int ret = 0;
if ( x < 0 ) {
isNegative = true;
x = -x;
}
i = 0;
while ( x != 0 ) {
str[i++] = x % 10 + '0';
x = x / 10;
}
str[i] = '\0';
if ( (isNegative && strlen(str) == 10 && strcmp(str, "2147483648") > 0) || (!isNegative && strlen(str) == 10 && strcmp(str, "2147483647") > 0) ) {
cout << "Out of range!" << endl;
throw new exception();
}
i = 0;
int strLen = (int)strlen(str);
while ( str[i] != '\0' ) {
ret += ((str[i] - '0') * pow(10.0, strLen - 1 - i));
i++;
}
return (isNegative ? -ret : ret);
}
};
This works:
public class Solution {
public int reverse(int x) {
long tmp = Math.abs((long)x);
long res = 0;
while(tmp >= 10){
res += tmp%10;
res*=10;
tmp=tmp/10;
}
res+=tmp;
if(x<0){
res = -res;
}
return (res>Integer.MAX_VALUE||res<Integer.MIN_VALUE)? 0: (int)res;
}
}
I tried to improve the performance a bit but all I could come up with was this:
public class Solution {
public int reverse(int x) {
long tmp = x;
long res = 0;
if(x>0){
while(tmp >= 10){
res += tmp%10;
res*=10;
tmp=tmp/10;
}
}
else{
while(tmp <= -10){
res += tmp%10;
res*=10;
tmp=tmp/10;
}
}
res+=tmp;
return (res>Integer.MAX_VALUE||res<Integer.MIN_VALUE)? 0: (int)res;
}
}
Its C# equivalent runs 5% faster than the 1st version on my machine, but their server says it is slower, which can't be - I got rid of extra function call here, otherwise it is essentially the same. It places me between 60-30% depending on the language (C# or Java). Maybe their benchmarking code is not very good - if you submit several times - resulting times vary a lot.
Solution In Swift 4.0 (in reference to problem from https://leetcode.com/problems/reverse-integer/description/)
func reverse(_ x : Int) -> Int {
var stringConversion = String(x)
var negativeCharacter = false
var finalreversedString = String()
let signedInt = 2147483647 //Max for Int 32
let unSignedInt = -2147483647 // Min for Int 32
if stringConversion.contains("-"){
stringConversion.removeFirst()
negativeCharacter = true
}
var reversedString = String(stringConversion.reversed())
if reversedString.first == "0" {
reversedString.removeFirst()
}
if negativeCharacter {
finalreversedString = "-\(reversedString)"
} else {
finalreversedString = reversedString
}
return (x == 0 || Int(finalreversedString)! > signedInt || Int(finalreversedString)! < unSignedInt) ? 0 : Int(finalreversedString)!
}
Last night, i have tried this same problem and i have found a simple solution in python, which is given below, here after checking the number type positive or negative, though i have tried in different section for both of them, i have convert the negative number into positive and before returning the reverse number, i had converted the number into negative.
For handling overflow, i have just simply checked with the upper limit of our 32-bit signed number and lower limit of the number, and it accepted my answer, thank you.
class Solution:
def reverse(self, x: int):
reverse = 0
if x > 0:
while x != 0:
remainder = x % 10
if reverse > (2147483647/10):
return 0
reverse = reverse * 10 + remainder
x = int(x / 10)
return reverse
elif x < 0:
x = x * (-1)
while x != 0:
remainder = x % 10
if reverse > ((2147483648)/10):
return 0
reverse = reverse * 10 + remainder
x = int(x / 10)
reverse = reverse * (-1)
return reverse
else:
return 0
public static int reverse(int x) {
boolean pos = x >= +0;
int y = (pos) ? x : -x;
StringBuilder sb = new StringBuilder(
String.valueOf(y));
sb.reverse();
int z = Integer.parseInt(sb.toString());
return pos ? z : -z;
}
public static void main(String[] args) {
for (int i = -10; i < 11; i++) {
System.out.printf("%d r= '%d'\n", i, reverse(i));
}
}
Outputs
-10 r= '-1'
-9 r= '-9'
-8 r= '-8'
-7 r= '-7'
-6 r= '-6'
-5 r= '-5'
-4 r= '-4'
-3 r= '-3'
-2 r= '-2'
-1 r= '-1'
0 r= '0'
1 r= '1'
2 r= '2'
3 r= '3'
4 r= '4'
5 r= '5'
6 r= '6'
7 r= '7'
8 r= '8'
9 r= '9'
10 r= '1'
Did you notice the reverse of 10 and -10? Or 20? You could just return a String, for example
public static String reverse(int x) {
boolean pos = x >= +0;
int y = (pos) ? x : -x;
StringBuilder sb = new StringBuilder(
String.valueOf(y));
sb.reverse();
if (!pos) {
sb.insert(0, '-');
}
return sb.toString();
}
public static void main(String[] args) {
for (int i = -10; i < 11; i++) {
System.out.printf("%d r= '%s'\n", i, reverse(i));
}
}
Works as I would expect.
If you are required to return a 32 bit int, and still need to know if there was an overflow perhaps you could use a flag as an extra parameter. If you were using c or c++ you could use pointers to set the flag, or in Java you can use an array (since Java objects pass by value).
Java example:
public class Solution {
public static int reverse(int x, Boolean[] overflowed) {
int ret = 0;
boolean zero = false;
boolean inputIsNegative = x < 0;
while (!zero) {
ret = ret * 10 + (x % 10);
x /= 10;
if(x == 0){
zero = true;
}
}
//Set the flag
if ( (inputIsNegative && (ret > 0)) || ((!inputIsNegative) && (ret < 0)))
overflowed[0] = new Boolean(true);
else
overflowed[0] = new Boolean(false);
return ret;
}
public static void main(String[] args) {
int s = 1000000004;
Boolean[] flag = {null};
System.out.println(s);
int n = reverse(s,flag); //reverse() will set the flag.
System.out.println(flag[0].booleanValue() ? "Error: Overflow": n );
}
}
Notice if the reversed number is too large for a 32 bit integer the flag will be set.
Hope this helps.
Use string to store the reverse and then print or use long or BigInt
public class Solution {
/**
* OVERFLOW
* #param x
* #return
*/
public int reverse(int x) {
int sign = x>0? 1: -1;
x *= sign;
int ret = 0;
while(x>0) {
ret *= 10;
if(ret<0 || x>10&&ret*10/10!=ret) // overflow
return 0;
ret += x%10;
x /= 10;
}
return ret*sign;
}
public static void main(String[] args) {
assert new Solution().reverse(-2147483412)==-2147483412;
}
}
public class Solution {
public int Reverse(int x) {
var sign = x < 0 ? -1 : 1;
var reverse = 0;
if (x == int.MinValue)
{
return 0;
}
x = Math.Abs(x);
while(x > 0)
{
var remainder = x % 10;
if (reverse > ((int.MaxValue - remainder)/10))
{
return 0;
}
reverse = (reverse*10) + remainder;
x = x/10;
}
return sign * Convert.ToInt32(reverse);
}
}
Here we will use long to handle the the over flow:
public class Solution {
public int reverse(int A) {
// use long to monitor Overflow
long result = 0;
while (A != 0) {
result = result * 10 + (A % 10);
A = A / 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return 0;
} else {
return (int) result;
}
}
}
Well This Suitable Code in Java Can be:-
public class Solution {
public int reverse(int x) {
int r;
long s = 0;
while(x != 0)
{
r = x % 10;
s = (s * 10) + r;
x = x/10;
}
if(s >= Integer.MAX_VALUE || s <= Integer.MIN_VALUE) return 0;
else
return (int)s;
}
}
My solution without using long:
public class ReverseInteger {
public static void main(String[] args) {
int input = Integer.MAX_VALUE;
int output = reverse(input);
System.out.println(output);
}
public static int reverse(int x) {
int remainder = 0;
int result = 0;
if (x < 10 && x > -10) {
return x;
}
while (x != 0) {
remainder = x % 10;
int absResult = Math.abs(result);
int maxResultMultipliedBy10 = Integer.MAX_VALUE / 10;
if (absResult > maxResultMultipliedBy10) {
return 0;
}
int resultMultipliedBy10 = absResult * 10;
int maxRemainder = Integer.MAX_VALUE - resultMultipliedBy10;
if (remainder > maxRemainder) {
return 0;
}
result = result * 10 + remainder;
x = x / 10;
}
return result;
}
}
here is the JavaScript solution.
/**
* #param {number} x
* #return {number}
*/
var reverse = function(x) {
var stop = false;
var res = 0;
while(!stop){
res = res *10 + (x % 10);
x = parseInt(x/10);
if(x==0){
stop = true;
}
}
return (res <= 0x7fffffff && res >= -0x80000000) ? res : 0
};
Taking care if the input is negative
public int reverse(int x)
{
long result = 0;
int res;
int num = Math.abs(x);
while(num!=0)
{
int rem = num%10;
result = result *10 + rem;
num = num / 10;
}
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
{
return 0;
}
else
{
res = (int)result;
return x < 0 ? -res : res;
}
}
This solution in Java will work:
class Solution {
public int reverse(int x) {
long rev = 0, remainder = 0;
long number = x;
while (number != 0) {
remainder = number % 10;
rev = rev * 10 + remainder;
number = number / 10;
}
if (rev >= Integer.MAX_VALUE || rev <= Integer.MIN_VALUE || x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE)
return 0;
else
return (int) rev;
}
}
Much simpler solution. Ensure that intermittent result does not exceed INT_MAX or get below INT_MIN
int reverse(int x) {
int y = 0;
while(x != 0) {
if ( (long)y*10 + x%10 > INT_MAX || (long)y*10 + x%10 < INT_MIN) {
std::cout << "overflow occurred" << '\n'
return 0;
}
y = y*10 + x%10;
x = x/10;
}
return y;
}
Here is the solution coded in JS(Javascript, it has passed all the 1032 test cases successfully in Leetcode for the problem (https://leetcode.com/problems/reverse-integer), also as asked in the question about the same.
/**
* #param {number} x
* #return {number}
*/
var reverse = function(x) {
let oldNum = x, newNum = 0, digits = 0, negativeNum = false;
if(oldNum < 0){
negativeNum = true;
}
let absVal = Math.abs(x);
while(absVal != 0){
let r = Math.trunc(absVal % 10);
newNum = (newNum*10) + r; digits++;
absVal = Math.floor(absVal/10);
}
if( !(newNum < Number.MAX_VALUE && newNum >= -2147483648 && newNum <= 2147483647)){
return 0;
}
return negativeNum ? -newNum :newNum;
};
Here is the solution coded in JS(Javascript, it has passed all the 1032 test cases successfully in Leetcode for the problem (https://leetcode.com/problems/reverse-integer), also as asked in the question about the same.
/**
* #param {number} x
* #return {number}
*/
var reverse = function(x) {
let oldNum = x, newNum = 0, digits = 0, negativeNum = false;
if(oldNum < 0){
negativeNum = true;
}
let absVal = Math.abs(x);
while(absVal != 0){
let r = Math.trunc(absVal % 10);
newNum = (newNum*10) + r; digits++;
absVal = Math.floor(absVal/10);
}
if( !(newNum < Number.MAX_VALUE && newNum >= -2147483648 && newNum <= 2147483647)){
return 0;
}
return negativeNum ? -newNum :newNum;
};
The earlier answer was posted by the same user (unregistered). Consider this one.
There are several good solutions posted. Here is my JS solution:
const reverse = function (x) {
const strReversed = x.toString().split("").reverse().join("");
rv =
parseInt(strReversed) > Math.pow(2, 31)
? 0
: Math.sign(x) * parseInt(strReversed);
return rv;
};
I got all 1032 cases to work in python, I don't know how to remove multiple 0's such as 100, 1000, 10000 etc thus I used my if statement multiple times lol.
class Solution:
def reverse(self, x: int) -> int:
string = ""
y = str(x)
ab = list(reversed(y))
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if ab[-1] == "-":
ab.remove("-")
ab.insert(0, "-")
for i in ab:
string += i
if int(string) > 2**31 - 1 or int(string) < -2**31:
return 0
return string
public static int reverse(int x) {
if (x == 0) return 0;
int sum = 0;
int y = 0;
while (x != 0) {
int value = (x % 10);
x = x - value;
y = sum;
sum = (sum * 10) + value;
if(sum / 10 != y) return 0;
x = x / 10;
}
return sum;
}
Extracting the first digit and dividing x to ten until x will be equal to 0. Therefore integer will be tokenized its digits.
Every extracted value will be adding the sum value after multiplying the sum by 10. Because adding a new digit means that adding a new 10th to the sum value. Also added if block to check any corruption of data because after 9th digit data will be corrupted.
1032 / 1032 test cases passed.
Status: Accepted
Runtime: 3 ms
Memory Usage: 38 MB
Public int reverse(int A) {
int N, sum = 0;
int rem = 0;
boolean flag = false;
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
if (A < 0) {
flag = true;
A = A * -1;} // 123 // 10 1
while (A > 0) {
rem = A % 10;
if (flag == true) {
if ((min + rem) / 10 > -sum) {
return 0;}}else{
if ((max - rem) / 10 < sum) {
return 0;}}
sum = (sum * 10) + rem;
A = A / 10;}
return (flag == true) ? —sum : sum;}}
#java #Algo
def reverse(self, x: int) -> int:
if x<=-2**31 or x>=2**31-1:
return 0
else:
result = 0
number = x
number = abs(number)
while (number) > 0:
newNumber = number % 10
result = result * 10 + newNumber
number = (number // 10)
if x<0:
result = "-"+str(result)
if int(result)<=-2**31:
return 0
return result
else:
if result>=2**31-1:
return 0
return result
if __name__ == '__main__':
obj = Solution()
print(obj.reverse(1534236469))
Note that there are previous solutions that do not work for input: 1000000045
try this:
public int reverse(int A) {
int reverse=0;
int num=A;
boolean flag=false;
if(A<0)
{
num=(-1)*A;
flag=true;
}
int prevnum=0;
while(num>0)
{
int currDigit=num%10;
reverse=reverse*10+currDigit;
if((reverse-currDigit)/10!=prevnum)
return 0;
num=num/10;
prevnum=reverse;
}
if(flag==true)
reverse= reverse*-1;
return reverse;
}

Categories

Resources