Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
I was trying to use the code below to solve the integer reverse problem. But when I convert the int to a string and then convert the string back to int, there is an error. I am wondering if the memory allocation limiting this method.
The error is Line 4: error: incompatible types: possible lossy conversion from long to int
public class Solution {
public long reverse(int x) {
String input = String.valueOf(x);
char[] num = input.toCharArray();
StringBuffer reverse = new StringBuffer();
if(x<0){
reverse.append("-");
for(int i=num.length-1;i>0;i--){
reverse.append(num[i]);
}
}else{
for(int i=num.length-1;i>=0;i--){
reverse.append(num[i]);
}
}
return Long.parseLong(reverse.toString());
}
}
It does what you have asked for.
public static long reverseInteger(int n){
String answer = "";
if (n == Integer.MIN_VALUE)
return -8463847412L;
boolean negative = false;
if (n < 0) {
negative = true;
n = -n;
}
while (n > 0) {
answer += (n % 10);
n = n/10;
}
long toReturn = Long.parseLong(answer);
return (negative) ? -toReturn : toReturn;
}
The static keyword is optional, of course.
It depends on how you use it.
The error message you are getting is probably due to somewhere else in your code; perhaps you are assigning the value returned by reverse() (which is a long) to an int variable.
However, there is unnecessary inefficiency in your code. You are creating a String, only to re-parse it back to a number. The following code returns a reversed number without using any strings at all:
public static long reverse(int n){
long r = 0;
while (n != 0) {
r *= 10;
r += (n % 10);
n /= 10;
}
return r;
}
Note that this method works correctly for negative numbers too, without having to check for them specially.
This method works for all possible int values.
Something like this works:
public long reverse(int x) {
String input = String.valueOf(x); //123
long result = Long.parseLong(new StringBuilder(input).reverse().toString());
return result; //321
}
Related
I'm trying to remove trailing zeroes from an integer and here is my code so far.
import java.math.BigInteger;
public class newuhu {
public static int numTrailingZeros(int s) {
BigInteger J = BigInteger.valueOf(s);
String sb = J.toString();
String Y = "";
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '0') {
sb.replaceAll("0"," ");
}
return Integer.parseInt(Y);
}
Note: I turned my int into a Biginteger because I've been warned that some inputs may look like 20!, which is 2.432902e+18
However, my IntelliJ debugging tool tells me that variable sb isn't in the loop. So, I'm trying to understand what must be done to make sure sb is in the loop.
Please understand that I'm a beginner in Java so, I'm trying to learn something new.
replaceAll replaces all occurrences of string with character that you want (ie space) so you don't need loop at all, also you're concerned about overflow so you should actually use BigInteger as a parameter, not int (int wont fit anything close to 20!) but there's another issue with your code, you said you want to replace trailing zeros but right now you will replace every 0 with blank character, you should try to use something like https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
public class newuhu {
public static int numTrailingZeros(BigInteger s) {
String sb = s.toString();
return Integer.parseInt(sb.replaceAll("0", "")); // consider returning something else if you're working with BigInteger
}
Keep in mind that when doing BigInteger.valueOf(int) does not have an effect as a number to big for int will never be stored in an int. Also 20! is fine for int.
public static String trimTrailingZeros(String source) {
for (int i = source.length() - 1; i > 0; ++i) {
char c = source.charAt(i);
if (c != '0') {
return source.substring(0, i + 1);
}
}
return ""; // or return "0";
}
Or if you prever BigInteger.
public static BigInteger trimTrailingZeros(BigInteger num) {
while (num.remainder(BigInteger.TEN).signum() == 0) {
num = num.divide(BigInteger.TEN);
}
return num;
}
This should be fast as you only create one string (via substring).
(First: variables and fields should start with a small letter - when no constants.)
It should be
sb = sb.replaceAll(...)
as sb is not changed by replaceAll, only the replaced value is returned. The class String gives immutable values, that always remain the same, so you can assign a variable to a variable and changing values of either variable will never influence the other - no further sharing.
Then it should be:
sb = sb.replaceFirst("0$", "");
replaceAll would replace every 0, like "23043500" to "23435".
replaceFirst replaces the _regular expression: char '0' at the end $.
Overflow on the input number is not possible, as you are already passing an int.
public static int numTrailingZeros(int n) {
while (n != 0 && n % 10 == 0) {
n /= 10;
}
return n;
}
public static int numTrailingZeros(String n) {
n = n.replaceAll("0+", "");
if (n.isEmpty() || n.equals("-")) { // "-0" for pessimists?
n = "0";
}
return Integer.parseInt(n);
}
% is the modulo operator, the remainder of an integer division 147 % 10 == 7.
The name is misleading, or you are calculating something different.
public static int numTrailingZeros(int n) {
int trailingZeros = 0;
while (n != 0 && n % 10 == 0) {
n /= 10;
++trailingZeros ;
}
return trailingZeros ;
}
The problem here is that sb.replaceAll("0","") won't do anything. You're throwing away the return value that contains your replaced string. See here.
What you probably want is something like this:
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == '0') {
sb = sb.replaceAll("0"," ");
I'm not sure you need a while loop, though. ReplaceAll will... replace all of the zeros with spaces.
Tried all the ways to pass the test case but it still shows only one error. I do not know how to rectify the error.
Input: 1534236469
Actual Output: 1056389759
Expected Output: 0
I do not know why my code does not give output 0.
class Solution
{
public static int reverse(int x)
{
boolean flag = false;
if (x < 0)
{
x = 0 - x;
flag = true;
}
int res = 0;
int p = x;
while (p > 0)
{
int mod = p % 10;
p = p / 10;
res = res * 10 + mod;
}
if (res > Integer.MAX_VALUE)
{
return 0;
}
if (flag)
{
res = 0 - res;
}
return res;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int revinteger = reverse(x);
System.out.println(revinteger);
}
}
The statement res > Integer.MAX_VALUE will never be true as res is of int datatype. And an int can never be larger than the Integer.MAX_VALUE (MAX_VALUE is itself the max we can store as int).
Use long datatype for reversing the number instead and at the end return the integer value of the result.
Because long based operations are relatively slow, I would only use a long to do the final check to determine if overflow is about to occur.
It should be obvious that no int will cause overflow if all the digits except the last are reversed. So process the last digit outside of the loop before returning the value. The border case for min is eliminated first to facilitate subsequent processing. Now only Integer.MAX_VALUE is of concern for both positive and negative numbers.
public static int reverse(int v) {
if (v == Integer.MIN_VALUE) {
return 0; // guaranteed overflow if reversed.
}
int rev = 0;
long ovflLimit = Integer.MAX_VALUE;
int sign = v < 0 ? -1 : 1;
v *=sign;
while (v > 9) {
int digit = v % 10;
rev = rev * 10 + digit;
v/=10;
}
long ovfl = (long)(rev)*10+v;
return ovfl > ovflLimit ? 0 : (int)(ovfl)*sign;
}
This problem can be solved in various ways but if we stick to Java and your solution then as it already have been pointed out in some of the answers that by using int the condition if(res > Integer.MAX_VALUE) will never be true.
Hence you would not get expected output as 0.
You can put a check before reversing last digit by casting the value in long and check if it's out of int limit. As suggested by WJS.
In case you want to stick to your solution without much change below is the working code for the same.
class Solution {
public static int reverse(int x) {
boolean flag = false;
long input = x;
if (input < 0) {
input = 0 - input;
flag = true;
}
long res = 0;
long p = input;
while (p > 0) {
long mod = p % 10;
p = p / 10;
res = res * 10 + mod;
}
if (res > Integer.MAX_VALUE) {
return 0;
}
if (flag) {
res = 0 - res;
}
return (int) res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int revInteger = reverse(x);
System.out.println(revInteger);
}
}
if (res > Integer.MAX_VALUE)
If it's the max possible value of the integer, how will it ever be greater than it? You'll have to detect it in another way.
One way would be to use the long data type instead of int. Then, it can become larger than Integer.MAX_VALUE, and that catch will work.
Otherwise, you can probably find another way to catch that case.
For homework, I have to write a program in java that converts a binary number that the user inputs (n) into a decimal number. I'm not allowed to use any cheat functions and stuff. This is the code for the static method I have so far:
public static int binarytodecimal(String n) {
int answer=0;
int digit=0;
int multiplier=1;
char index=n.charAt(digit);
int length=n.length();
while (index=='0' || index=='1' && digit<=length) {
if (index=='1') {
answer+=multiplier;
multiplier*=2;
digit+=1;
}
else {
multiplier*=2;
digit+=1;
}
}
return answer;
}
For example, if n was 1, I keep getting 3 when the answer should be 1. I'm not sure where I went wrong.
first of all, you should iterate through n in reverse mode (test something like n="1101" and you will see) then inside your loop read bits at each position
public static int binarytodecimal(String n) {
int answer = 0;
int digit = n.length();
int multiplier = 1;
while (digit > 0) {
char index = n.charAt(digit - 1);
if (index == '1') {
answer += multiplier;
multiplier *= 2;
digit--;
} else {
multiplier *= 2;
digit--;
}
}
return answer;
}
The method below was written to make a String version of a number, I know there are already methods that do this, such as String.valueOf(), Double.toString(), or even just "" + someNumber.
private static String numToString(double i) {
String revNumber = "";
boolean isNeg = false;
if (i == 0) { //catch zero case
return "0";
}
if (i < 0) {
isNeg = true;
}
i = Math.abs(i);
while (i > 0) { //loop backwards through number, this loop
//finish, otherwise, i would not get any output in 'main()'
revNumber += "" + i % 10; //get the end
i /= 10; //slice end
}
String number = ""; //reversed
for (int k = revNumber.length() - 1; k >= 0; k--) {
number += revNumber.substring(k, k + 1);
}
revNumber = null; //let gc do its work
return isNeg ? "-" + number : number; //result expression to add "-"
//if needed.
}
Although the above method should only be used for ints (32-bit), I made it accept a double (64-bit) argument and I passed a double argument, without a decimal, the output results are the same if I pass an int into the method as well, or with a decimals, etc...
Test:
public static void main(String[] args) {
double test = -134; //Passing double arg
System.out.println(numToString(test)); //results
}
Result: (Maximum memory results for double?):
-323-E5.1223-E33.1123-E43.1023-E43.1913-E43.1813-E43.1713-E43.1613-E43.1513-E43.1413-E43.1313-E43.1213-E43.1113-E43.1013-E43.1903-E43.1803-E999999999999933.1703-E999999999999933.1603-E999999999999933.1503-E999999999999933.1403-E9899999999999933.1303-E999999999999933.1203-E999999999999933.1103-E8899999999999933.1003-E9899999999999933.1992-E999999999999933.1892-E999999999999933.1792-E999999999999933.1692-E999999999999933.1592-E999999999999933.1492-E999999999999933.1392-E999999999999933.1292-E999999999999933.1192-E999999999999933.1092-E999999999999933.1982-E999999999999933.1882-E1999999999999933.1782-E999999999999933.1682-E999999999999933.1582-E999999999999933.1482-E999999999999933.1382-E999999999999933.1282-E1999999999999933.1182-E1999999999999933.1082-E2999999999999933.1972-E2999999999999933.1872-E3999999999999933.1772-E2999999999999933.1672-E1999999999999933.1572-E2999999999999933.1472-E999999999999933.1372-E999999999999933.1272-E1999999999999933.1172-E2999999999999933.1072-E2999999999999933.1962-E1999999999999933.1862-E999999999999933.1762-E999999999999933.1662-E999999999999933.1562-E999999999999933.1462-E999999999999933.1362-E999999999999933.1262-E999999999999933.1162-E999999999999933.1062-E999999999999933.1952-E999999999999933.1852-E999999999999933.1752-E999999999999933.1652-E999999999999933.1552-E999999999999933.1452-E999999999999933.1352-E999999999999933.1252-E999999999999933.1152-E999999999999933.1052-E9899999999999933.1942-E9899999999999933.1842-E999999999999933.1742-E999999999999933.1642-E999999999999933.1542-E999999999999933.1442-E999999999999933.1342-E999999999999933.1242-E999999999999933.1142-E9899999999999933.1042-E999999999999933.1932-E8899999999999933.1832-E9899999999999933.1732-E8899999999999933.1632-E8899999999999933.1532-E8899999999999933.1432-E999999999999933.1332-E9899999999999933.1232-E8899999999999933.1132-E7899999999999933.1032-E8899999999999933.1922-E8899999999999933.1822-E7899999999999933.1722-E6899999999999933.1622-E5899999999999933.1522-E5899999999999933.1422-E6899999999999933.1322-E6899999999999933.1222-E6899999999999933.1122-E7899999999999933.1022-E7899999999999933.1912-E7899999999999933.1812-E8899999999999933.1712-E8899999999999933.1612-E7899999999999933.1512-E7899999999999933.1412-E6899999999999933.1312-E6899999999999933.1212-E7899999999999933.1112-E7899999999999933.1012-E7899999999999933.1902-E7899999999999933.1802-E6899999999999933.1702-E7899999999999933.1602-E7899999999999933.1502-E8899999999999933.1402-E8899999999999933.1302-E8899999999999933.1202-E8899999999999933.1102-E7899999999999933.1002-E7899999999999933.1991-E9899999999999933.1891-E9899999999999933.1791-E8899999999999933.1691-E7899999999999933.1591-E8899999999999933.1491-E8899999999999933.1391-E999999999999933.1291-E9899999999999933.1191-E9899999999999933.1091-E999999999999933.1981-E999999999999933.1881-E999999999999933.1781-E999999999999933.1681-E999999999999933.1581-E1999999999999933.1481-E999999999999933.1381-E999999999999933.1281-E1999999999999933.1181-E2999999999999933.1081-E999999999999933.1971-E1999999999999933.1871-E999999999999933.1771-E2999999999999933.1671-E3999999999999933.1571-E3999999999999933.1471-E2999999999999933.1371-E2999999999999933.1271-E2999999999999933.1171-E999999999999933.1071-E999999999999933.1961-E999999999999933.1861-E999999999999933.1761-E999999999999933.1661-E999999999999933.1561-E999999999999933.1461-E8899999999999933.1361-E8899999999999933.1261-E8899999999999933.1161-E7899999999999933.1061-E7899999999999933.1951-E7899999999999933.1851-E7899999999999933.1751-E7899999999999933.1651-E7899999999999933.1551-E6899999999999933.1451-E6899999999999933.1351-E6899999999999933.1251-E6899999999999933.1151-E6899999999999933.1051-E7899999999999933.1941-E6899999999999933.1841-E7899999999999933.1741-E7899999999999933.1641-E9899999999999933.1541-E999999999999933.1441-E999999999999933.1341-E999999999999933.1241-E999999999999933.1141-E999999999999933.1041-E999999999999933.1931-E9899999999999933.1831-E999999999999933.1731-E999999999999933.1631-E8899999999999933.1531-E9899999999999933.1431-E9899999999999933.1331-E8899999999999933.1231-E8899999999999933.1131-E8899999999999933.1031-E7899999999999933.1921-E7899999999999933.1821-E7899999999999933.1721-E6899999999999933.1621-E7899999999999933.1521-E7899999999999933.1421-E8899999999999933.1321-E7899999999999933.1221-E7899999999999933.1121-E8899999999999933.1021-E8899999999999933.1911-E9899999999999933.1811-E999999999999933.1711-E999999999999933.1611-E999999999999933.1511-E999999999999933.1411-E1999999999999933.1311-E2999999999999933.1211-E3999999999999933.1111-E2999999999999933.1011-E2999999999999933.1901-E3999999999999933.1801-E2999999999999933.1701-E2999999999999933.1601-E3999999999999933.1501-E2999999999999933.1401-E3999999999999933.1301-E3999999999999933.1201-E4999999999999933.1101-E5999999999999933.1001-E4999999999999933.199-E3999999999999933.189-E3999999999999933.179-E3999999999999933.169-E4999999999999933.159-E4999999999999933.149-E4999999999999933.139-E4999999999999933.129-E4999999999999933.119-E4999999999999933.109-E4999999999999933.198-E4999999999999933.188-E4999999999999933.178-E3999999999999933.168-E3999999999999933.158-E3999999999999933.148-E3999999999999933.138-E3999999999999933.128-E4999999999999933.118-E3999999999999933.108-E3999999999999933.197-E3999999999999933.187-E3999999999999933.177-E4999999999999933.167-E3999999999999933.157-E3999999999999933.147-E3999999999999933.137-E3999999999999933.127-E3999999999999933.117-E4999999999999933.107-E5999999999999933.196-E5999999999999933.186-E5999999999999933.176-E4999999999999933.166-E4999999999999933.156-E4999999999999933.146-E4999999999999933.136-E3999999999999933.126-E3999999999999933.116-E3999999999999933.106-E3999999999999933.195-E2999999999999933.185-E1999999999999933.175-E2999999999999933.165-E2999999999999933.155-E2999999999999933.145-E2999999999999933.135-E3999999999999933.125-E4999999999999933.115-E4999999999999933.105-E2999999999999933.194-E1999999999999933.184-E2999999999999933.174-E2999999999999933.164-E2999999999999933.154-E1999999999999933.144-E1999999999999933.134-E2999999999999933.124-E2999999999999933.114-E2999999999999933.104-E3999999999999933.193-E3999999999999933.183-E3999999999999933.173-E2999999999999933.163-E2999999999999933.153-E999999999999933.143-E2999999999999933.133-E2999999999999933.123-E2999999999999933.113-E3999999999999933.103-E3999999999999933.192-E3999999999999933.182-E3999999999999933.172-E3999999999999933.162-E4999999999999933.152-E4999999999999933.142-E5999999999999933.132-E6999999999999933.122-E7999999999999933.112-E6999999999999933.102-E6999999999999933.191-E7999999999999933.181-E8999999999999933.171-E8999999999999933.161-E8999999999999933.151-E9999999999999933.141-E8999999999999933.131-E8999999999999933.121-E43.111-E43.101-E43.19-E1000000000000043.18-E1000000000000043.17-E43.16-E43.15-E43.14-E43.143100.04310.0431.043.14000000000000004.30.4
This is not because of the complier. It is happening because you are doing
i /= 10; //slice end
So when you do 13.4 after the first run it wont give you 1.34 it will give you something like 1.339999999999999999 which is 1.34.
Check Retain precision with double in Java for more details.
If you just want to reverse the number you can do
private static String numToString(double i) {
String returnString = new StringBuilder(Double.toString(i)).reverse().toString();
return i>=0?returnString:"-"+returnString.substring(0,returnString.length()-1);
}
for (; i > 0; ) { //loop backwards through number
revNumber += "" + i % 10; //get the end
i /= 10; //slice end
}
This loop never finishes until it breaks at a much later time than it should. i % 10 doesn't cut off the end of a double. It works well with an int but not with a double. Hence the 134->13.4->1.34->.134-> etc.... So you get an argumentoutofrange exception or something similar to that. Else the compiler just keeps doing it for the max memory that a double can handle.
I am trying to write a function in Java that returns the greatest digit in a number using recursion.
I have managed to do it using two parameters, the number and greater digit.
Initially the greater digit parameter accepts value as 0.
static int getGreatestDigit(int num , int greater){
if(num != 0){
if(num %10 > greater){
greater = num%10;
num = num/10;
return getGreatestDigit(num , greater);
}else{
num = num/10;
return getGreatestDigit(num , greater);
}
}
return greater;
}
I want to write same recursive function but with only one parameter that is number.
Like
int getGreatestDigit(int num){
//code
}
I am stuck at logic. How to do that?
Only the first call to getGreatestDigit(num) needs to keep track of the greater result. Each recursive call to getGreatestDigit(num) will return the greatest digit in the part of the original number that it is tasked with scanning. The very first invocation of getGreatestDigit(num) can compare the number it took with the greatest number returned from all recursive calls.
int getGreatestDigit(int num)
{
if (num == 0) return 0;
int lastNum = num % 10;
int otherDigits = num / 10;
int recursiveLastNum = getGreatestDigit(otherDigits);
return Math.Max(lastNum, recursiveLastNum);
}
static int getGreatestDigit(int num)
{
return num == 0 ? 0 :
Math.Max(num % 10, getGreatestDigit(num / 10));
}
So basically, you look at the least significant digit each time, comparing it against the maximum of the rest of the digits.
You can do this, if you use the functions stack as temporary memory to hold your interim results, i.e. what was previously stored in the greater parameter.
This changes your function to be no longer tail recursive, making it worse performance wise.
int greatestDigit(int num) {
int last = num % 10;
int rest = num / 10;
if (rest == 0) {
return last;
} else {
int candidate = greatestDigit (rest);
if (candidate > last) {
return candidate;
} else {
return last;
}
}
}
/** Pseudocode:
1. if num > 9, /10 and call getGreatestDigit on that (recursive step). Then get the current digit (undivided) and return the greater of the two
2. if num <= 9, return num
*/
int getGreatestDigit(int num){
//code
}
package Map;
import java.util.ArrayList;
public class Practice8 {
public int highestDigit(int number){
ArrayList<Integer> temp= new ArrayList<>();
StringBuilder sb= new StringBuilder();
sb.append(number);
String value= sb.toString();
for(int i=0;i<value.length();i++){
temp.add((int)value.charAt(i)-'0');
}
int max=0;
for(int x: temp){
if(x>max){
max=x;
}
}
return max;
}
public static void main(String[] args) {
Practice8 practice8= new Practice8();
System.out.println(practice8.highestDigit(379));
}
}