Reversing a Number using bitwise shift - java

I am trying to find a way to reverse a number without
Converting it to a string to find the length
Reversing the string and parsing it back
Running a separate loop to compute the Length
i am currently doing it this way
public static int getReverse(int num){
int revnum =0;
for( int i = Integer.toString(num).length() - 1 ; num>0 ; i-- ){
revnum += num % 10 * Math.pow( 10 , i );
num /= 10;
}
return revnum;
}
But I would Like to implement the above 3 conditions.
I am looking for a way , possibly using the bit wise shift operators or some other kind of bitwise operation.
Is it possible ? If so how ?
PS : If 1234 is given as input it should return 4321. I will only be reversing Integers and Longs

How about:
int revnum = 0;
while (num != 0) {
revnum = revnum * 10 + (num % 10);
num /= 10;
}
return revnum;
The code expects a non-negative input.
This may or may not matter to you, but it's worth noting that getReverse(getReverse(x)) does not necessarily equal x as it won't preserve trailing zeroes.

How about this? It handles negative numbers as well.
public int getReverse(int num){
int rst=0;
int sign;
sign=num>0?1:-1;
num*=sign;
while(num>0){
int lastNum = num%10;
rst=rst*10+lastNum
num=num/10;
}
return rst*sign;
}

Integer.MAX_VALUE or Integer.MIN_VALUE is not at all considered in any of the solutions.
For eg: if the input is -2147483647 or 2147483647 the o/p will be 1126087180 and -1126087180 respectively.
Please try the below solutions where both the conditions are handled, so if at any point of time the number is going beyond the boundary conditions i.e., INPUT_VALUE > Integer.MAX_VALUE or INPUT_VALUE < Integer.MIN_VALUE it would return 0
class ReversingIntegerNumber {
public int reverse(int originalNum) {
boolean originalIsNegative = originalNum > 0 ? false : true;
int reverseNum = 0;
int modValue;
originalNum = Math.abs(originalNum);
while(originalNum != 0) {
modValue = originalNum % 10;
if(reverseNum > (Integer.MAX_VALUE - modValue)/10) {
return 0;
}
reverseNum = (reverseNum * 10) + modValue;
originalNum /= 10;
}
return originalIsNegative ? -1 * reverseNum : reverseNum;
}
}

Related

How to print an integer with commas every 'd' digits, from right to left

I had to write a program that will receive an int 'n' and another one 'd' - and will print the number n with commas every d digits from right to left.
If 'n' or 'd' are negative - the program will print 'n' as is.
I although had to make sure that there is no commas before or after the number and I'm not allowed to use String or Arrays.
for example: n = 12345678
d=1: 1,2,3,4,5,6,7,8
d=3: 12,345,678
I've written the following code:
public static void printWithComma(int n, int d) {
if (n < 0 || d <= 0) {
System.out.println(n);
} else {
int reversedN = reverseNum(n), copyOfrereversedN = reversedN, counter = numberLength(n);
while (reversedN > 0) {
System.out.print(reversedN % 10);
reversedN /= 10;
counter--;
if (counter % d == 0 && reversedN != 0) {
System.out.print(",");
}
}
/*
* In a case which the received number will end with zeros, the reverse method
* will return the number without them. In that case the length of the reversed
* number and the length of the original number will be different - so this
* while loop will end the zero'z at the right place with the commas at the
* right place
*/
while (numberLength(copyOfrereversedN) != numberLength(n)) {
if (counter % d == 0) {
System.out.print(",");
}
System.out.print(0);
counter--;
copyOfrereversedN *= 10;
}
}
}
that uses a reversNum function:
// The method receives a number n and return his reversed number(if the number
// ends with zero's - the method will return the number without them)
public static int reverseNum(int n) {
if (n < 9) {
return n;
}
int reversedNum = 0;
while (n > 0) {
reversedNum += (n % 10);
reversedNum *= 10;
n /= 10;
}
return (reversedNum / 10);
}
and numberLength method:
// The method receives a number and return his length ( 0 is considered as "0"
// length)
public static int numberLength(int n) {
int counter = 0;
while (n > 0) {
n /= 10;
counter++;
}
return counter;
}
I've been told that the code doesn't work for every case, and i am unable to think about such case (the person who told me that won't tell me).
Thank you for reading!
You solved looping through the digits by reversing the number, so a simple division by ten can be done to receive all digits in order.
The comma position is calculated from the right.
public static void printWithComma(int n, int d) {
if (n < 0) {
System.out.print('-');
n = -n;
}
if (n == 0) {
System.out.print('0');
return;
}
int length = numberLength(n);
int reversed = reverseNum(n);
for (int i = 0; i < length; ++i) {
int nextDigit = reversed % 10;
System.out.print(nextDigit);
reversed /= 10;
int fromRight = length - 1 - i;
if (fromRight != 0 && fromRight % d == 0) {
System.out.print(',');
}
}
}
This is basically the same code as yours. However I store the results of the help functions into variables.
A zero is a special case, an exception of the rule that leading zeros are dropped.
Every dth digit (from right) needs to print comma, but not entirely at the right. And not in front. Realized by printing the digit first and then possibly the comma.
The problems I see with your code are the two while loops, twice printing the comma, maybe? And the println with a newline when <= 0.
Test your code, for instance as:
public static void main(String[] args) {
for (int n : new int[] {0, 1, 8, 9, 10, 234,
1_234, 12_345, 123_456, 123_456_789, 1_234_567_890}) {
System.out.printf("%d : ", n);
printWithComma(n, 3);
System.out.println();
}
}
Your code seems overly complicated.
If you've learned about recursion, you can do it like this:
public static void printWithComma(int n, int d) {
printInternal(n, d, 1);
System.out.println();
}
private static void printInternal(int n, int d, int i) {
if (n > 9) {
printInternal(n / 10, d, i + 1);
if (i % d == 0)
System.out.print(',');
}
System.out.print(n % 10);
}
Without recursion:
public static void printWithComma(int n, int d) {
int rev = 0, i = d - 1;
for (int num = n; num > 0 ; num /= 10, i++)
rev = rev * 10 + num % 10;
for (; i > d; rev /= 10, i--) {
System.out.print(rev % 10);
if (i % d == 0)
System.out.print(',');
}
System.out.println(rev);
}
Are you allowed to use the whole Java API?
What about something as simple as using DecimalFormat
double in = 12345678;
DecimalFormat df = new DecimalFormat( ",##" );
System.out.println(df.format(in));
12,34,56,78
Using...
,# = 1 per group
,## = 2 per group
,### = 3 per group
etc...
It took me a bunch of minutes. The following code snippet does the job well (explanation below):
public static void printWithComma(int n, int d) { // n=number, d=commaIndex
final int length = (int) (Math.log10(n) + 1); // number of digits;
for (int i = 1; i < Math.pow(10, length); i*=10) { // loop by digits
double current = Math.log10(i); // current loop
double remains = length - current - 1; // loops remaining
int digit = (int) ((n / Math.pow(10, remains)) % 10); // nth digit
System.out.print(digit); // print it
if (remains % d == 0 && remains > 0) { // add comma if qualified
System.out.print(",");
}
}
}
Using (Math.log10(n) + 1) I find a number of digits in the integer (8 for 12345678).
The for-loop assures the exponents of n series (1, 10, 100, 1000...) needed for further calculations. Using logarithm of base 10 I get the current index of the loop.
To get nth digit is a bit tricky and this formula is based on this answer. Then it is printed out.
Finally, it remains to find a qualified position for the comma (,). If modulo of the current loop index is equal zero, the dth index is reached and the comma can be printed out. Finally the condition remains > 0 assures there will be no comma left at the end of the printed result.
Output:
For 4: 1234,5678
For 3: 12,345,678
For 2: 12,34,56,78
For 1: 1,2,3,4,5,6,7,8

Divide two integers without using multiplication, division and mod operator in java

I write down a code which find out quotient after dividing two number but without using multiplication,division or mod operator.
My code
public int divide(int dividend, int divisor) {
int diff=0,count=0;
int fun_dividend=dividend;
int fun_divisor=divisor;
int abs_dividend=abs(dividend);
int abs_divisor=abs(divisor);
while(abs_dividend>=abs_divisor){
diff=abs_dividend-abs_divisor;
abs_dividend=diff;
count++;
}
if(fun_dividend<0 && fun_divisor<0){
return count;
}
else if(fun_divisor<0||fun_dividend<0) {
return (-count);
}
return count;
}
My code passes the test cases like dividend=-1, divisor=1 or dividend=1 and divisor=-1. But it cannot pass the test case like dividend = --2147483648 and divisor =-1. However I have a if statement when both inputs are negative.
if(fun_dividend<0 && fun_divisor<0){
return count;
}
When my inputs are -2147483648 and -1 it returned zero. I debugged my code and find out that it cannot reach the the inner statements of while loop. It just check the while loop and terminated and execute
if(fun_dividend<0 && fun_divisor<0){
return count;
}
It is very obvious, both inputs are negative, so I was using Math.abs function to make them positive. But when I try to see the values of variables abs_dividend and abs_divisor they show me negative values.
Integer max can take a 9 digit number. So how could I pass this test case? As per this test case dividend is a 10 digit number which is not valid for a integer range.
As per the test case the output that I get should be 2147483647.
How could I solve the bug?
Thank you in advance.
Try using the bit manipulation for this as follows:
public static int divideUsingBits(int dividend, int divisor) {
// handle special cases
if (divisor == 0)
return Integer.MAX_VALUE;
if (divisor == -1 && dividend == Integer.MIN_VALUE)
return Integer.MAX_VALUE;
// get positive values
long pDividend = Math.abs((long) dividend);
long pDivisor = Math.abs((long) divisor);
int result = 0;
while (pDividend >= pDivisor) {
// calculate number of left shifts
int numShift = 0;
while (pDividend >= (pDivisor << numShift)) {
numShift++;
}
// dividend minus the largest shifted divisor
result += 1 << (numShift - 1);
pDividend -= (pDivisor << (numShift - 1));
}
if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
return result;
} else {
return -result;
}
}
I solve it this way. Give preference to data type long over int wherever there is a chance of overflow upon left-shift. Handle the edge case at the very beginning to avoid the input values getting modified in the process. This algorithm is based upon the division technique we used to make use in school.
public int divide(int AA, int BB) {
// Edge case first.
if (BB == -1 && AA == Integer.MIN_VALUE){
return Integer.MAX_VALUE; // Very Special case, since 2^31 is not inside range while -2^31 is within range.
}
long B = BB;
long A = AA;
int sign = -1;
if ((A<0 && B<0) || (A>0 && B>0)){
sign = 1;
}
if (A < 0) A = A * -1;
if (B < 0) B = B * -1;
int ans = 0;
long currPos = 1; // necessary to be long. Long is better for left shifting.
while (A >= B){
B <<= 1; currPos <<= 1;
}
B >>= 1; currPos >>= 1;
while (currPos != 0){
if (A >= B){
A -= B;
ans |= currPos;
}
B >>= 1; currPos >>= 1;
}
return ans*sign;
}
Ran with the debugger and found that abs_dividend was -2147483648.
Then the comparison in while (abs_dividend >= abs_divisor) { is false and count is never incremented.
Turns out the explanation is in the Javadoc for Math.abs(int a):
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
Presumably, this is because Integer.MAX_VALUE is 2147483647, so there is no way of representing positive 2147483648 with an int. (note: 2147483648 would be Integer.MAX_VALUE + 1 == Integer.MIN_VALUE)

Java integer overflow

I'm totally new to Java and I'm implementing a simple function to convert string to integer on Leetcode.
public int myAtoi(String str) {
if(str.length() == 0){
return 0;
}
str = str.trim();
int n = str.length();
int signal = 0;
if(n == 1 && str.equals("+") || str.equals("-")){
return 0;
}
if(str.charAt(0) == '+'){
signal = 1;
}else if(str.charAt(0) == '-'){
signal = -1;
}
int i = (signal != 0)? 1 : 0;
if(signal == 0){
signal = 1;//default
}
int res = 0;
while(i < n){
char c = str.charAt(i);
if(!Character.isDigit(c)){
return res * signal;
}
//res = res * 10 + c - '0';
if(signal * res > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(signal * res < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
res = res * 10 + c - '0';
++i;
}
return res * signal;
}
I know java integer has the MAX_VALUE of 2147483647. When my input is 2147483648 the output should be 2147483647 but indeed it's -214748648. I really have no idea what's wrong in here. Can anybody help me to understand this?
Consider this example
public static void main(String args[]) {
int i=2147483647;
System.out.println("i="+i);
int j=++i;
System.out.println("Now i is="+i);
System.out.println("j="+j);
}
What happens?
output will be :
i = 2147483647
Now i is=-2147483648
j=-2147483648
The maximum value of integer is 2,147,483,647 and the minimum value is -2,147,483,648. Here in j (with post increment of i), we have crossed the maximum limit of an integer
This is exactly what is happening in your case too .
Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE
Why?
Integer values are represented in binary form, and there is binary addition in java. It uses a representation called two's complement, in which the first bit of the number represents its sign. Whenever you add 1 to the largest Integer(MAX INT), which has a bit sign of 0, then its bit sign becomes 1 and the number becomes negative.
So, don't put > MAX INT as input, else put a condition in your code to check it on input itself.
The input is never +2147483648 since that value can't be represented as a Java int.
It will wrap around to the negative number you observe, so accounting for that result.

Comparing integers and creating the smallest integer possible from the digits of the given integers

I need to write the following method: accepts two integer parameters and returns an integer. If either integer is not a 4 digit number than the method should return the smaller integer. Otherwise, the method should return a four digit integer made up of the smallest digit in the thousands place, hundreds place, tens place and ones place. We cannot turn the integers into Strings, or use lists, or arrays.
For example biggestLoser(6712,1234) returns 1212
For example biggestLoser(19,8918) returns 19
Here's how I've started to write it:
public static int biggestLoser(int a, int b){
if(a<9999 || b<9999){
if(a<b)
return a;
else if(b<a)
return b;
}
int at=a/1000;
int ah=a%1000/100;
int an=a%100/10;
int ae=a%10;
int bt=b/1000;
int bh=b%1000/100;
int bn=b%100/10;
int be=a%10;
if(at<bt && ah<bh && an<bn && ae<be)
return at*1000+ah*100+an*10+ae;
else if(at<bt && ah<bh && an<bn && be<ae)
return at*1000+ah*100+an*10+be;
else if(at<bt&& ah<bh && bn<an && ae<be)
else return at*1000+ah*100+bn*10+ae;
However, it looks like I'm going to have to write way too many if statements, is there a shorter way to write the code?
public static int biggestLoser(int a, int b) {
if (a < 1000 || a >= 10000 || b < 1000 || b >= 10000) {
return Math.min(a, b);
} else {
// both a and b are four digits
int result = 0 ;
int multiplier = 1 ;
for (int digit = 0; digit < 4; digit++) {
int nextDigit = Math.min(a % 10, b % 10);
result = result + nextDigit * multiplier ;
multiplier = multiplier * 10 ;
a = a / 10 ;
b = b / 10 ;
}
return result ;
}
}
How does this work? a % 10 is the remainder when a is divided by 10: in other words it is the least significant digit of a (the "ones place").
a = a / 10 performs integer division, so it divides a by 10 and ignores any fraction. So 1234 becomes 123, and on the next iteration 123 becomes 12, etc. In other words, it discards the "ones place".
So the first time through the loop, you look at the "ones" from a and b, find the smallest one, and add it to result. Then you drop the "ones" from both a and b. So what used to be the "tens" are now the "ones". The second time through the loop, you get the smallest "ones" again: but this was originally the smallest "tens". You want to add that to result, but you need to multiply by 10. This is the multiplier: each time through the loop the multiplier is multiplied by 10. So each time, you get the smallest "ones", multiply by the correct thing, add to the result, and then drop the "ones" from a and b.
Just for fun, here's an implementation that needs only one statement (and works if you replace "four digits" with any positive number of digits). You can ask your instructor to explain it ;).
public static final int NUM_DIGITS = 4 ;
public static final int MAX = (int) Math.pow(10, NUM_DIGITS) ;
public static final int MIN = MAX / 10 ;
public static int biggestLoser(int a, int b) {
return (a < MIN || a >= MAX || b < MIN || b >= MAX) ? Math.min(a, b) :
IntStream.iterate(1, multiplier -> multiplier * 10).limit(NUM_DIGITS)
.map(multiplier -> Math.min((a / multiplier) % 10, (b / multiplier) % 10) * multiplier )
.sum();
}
maybe it is stupid but try to take advantage of String ( .charAt(int index) )and Integer ( .parseInt( String value ) ) methods , maybe this example help you :
int x=145;
int y=826;
//to know which number have the biggest tens
String a=x+"";
String b=y+"";
if(Integer.parseInt(a.charAt(1)+"")>Integer.parseInt(b.charAt(1)+""))
{
System.out.println("The number which have the biggest tens is "+a);
}
else
{
System.out.println("The number which have the biggest tens is "+b);
}
Using String and StringBuilder
public class Test
{
public static void main(String []args)
{
System.out.println(biggestLooser(6712,1234));
}
public static int biggestLooser(int _a, int _b)
{
String a = String.valueOf(_a);
String b = String.valueOf(_b);
StringBuilder c = new StringBuilder();
if(a.length() < b.length()) return Integer.parseInt(a);
else if(b.length() < a.length()) return Integer.parseInt(b);
else if(a.length() >= 4 && b.length() >= 4)
{
for(int i = 4; i > 0; i--)
{
char ch = '\0';
if(a.charAt(a.length() - i) < b.charAt(b.length() - i))
ch = a.charAt(a.length() - i);
else ch = b.charAt(b.length() - i);
c.append(ch);
}
return Integer.parseInt(c.toString());
}
else return -1;
}
}
//ouput: 1212
Here is the simple answer
public static int biggestLoser(int a, int b) {
if (a < 1000 || b < 1000) {
if (a < b)
return a;
else
return b;
}
int val = 0;
ArrayList<Integer> data1 = new ArrayList<Integer>();
while (a > 0) {
data1.add(a % 10);
a /= 10;
}
Collections.reverse(data1);
ArrayList<Integer> data2 = new ArrayList<Integer>();
while (b > 0) {
data2.add(b % 10);
b /= 10;
}
Collections.reverse(data2);
val = ((data1.get(0) < data2.get(0)) ? data1.get(0) : data2.get(0))
* 1000
+ ((data1.get(1) < data2.get(1)) ? data1.get(1) : data2.get(1))
* 100
+ ((data1.get(2) < data2.get(2)) ? data1.get(2) : data2.get(2))
* 10
+ ((data1.get(3) < data2.get(3)) ? data1.get(3) : data2.get(3));
return val;
}

How can I truncate a number from the left in Java without using String

I was wondering if anyone knew how to use mathematics to truncate a number from the left (remove digits one by one starting from the left).
I can use a simple division to truncate digits from the right:
int num = 10098;
while (num > 0){
System.out.println(num);
num /= 10;
}
This will output what I want:
10098
1009
100
10
1
But does anyone know a way to do this the other way around on integers and to truncate digits from the left without converting to String?
Try n = n % (int) Math.pow(10, (int) Math.log10(n));. Found here.
public void test() {
int n = 10098;
while (n > 0) {
System.out.println("n=" + n);
n = n % (int) Math.pow(10, (int) Math.log10(n));
}
}
prints
n=10098
n=98
n=8
int in = ...;
//the first number n : 10^n > in
int mostSignificantDigit = 1;
int digits = 1;
while(mostSignificantDigit < in)
{
mostSignificantDigit *= 10;
digits++;
}
//create the numbers
int[] result = new int[digits];
int count = 0;
while(mostSignificantDigit != 0){
result[count] = in % mostSignificantDigit;
mostSignificantDigit /= 10;
}
You can use the module operation %. The module is the remainder of the division.
You have to call it with with power of 10. So 10, 100, 1000, 10000
You can do it
int num = 10098;
int divided = num;
int module = 1;
while (divided > 0) {
divided /= 10;
module *= 10;
System.out.println(num % module);
}
Please note that if you don't left padding with zeros you will obtain 98 instead of 0098 or 098.

Categories