Changing numbers places in java - java

Can anyone please learn me how to change this number 5486 to 4568 ? I need to change two pairs of numbers places. Any ideas please?
My code :
public Number shiftRight(int n) {
int length = (getNumOfDigits()+MINUSONE);
length = (int) Math.pow(TEN, length);
for (int i=0; i<n; i++){
int m=num%TEN;
num=(m*length) + (num/TEN);
}
return new Number(num);
}
public int shiftRightDistance(Number other){
int max = getNumOfDigits();
for (int i=0;i<max;i++)
{
if(compareTo(shiftRight(i))==ZERO)
{
return i;
}
}
return MINUSONE;
}
public Number swapPairs() {
}
}

The simplest (and least confusing) thing might be to convert the number to a char array, swap pairs of characters, and then convert back to a number. You can use String.valueOf(int), String.toCharArray(), new String(char[]) and Integer.valueOf(String) to put that together.
Alternatively, you can build on the following method that swaps the digits of a non-negative number less than 100:
private int swapDigitsLessThan100(int n) {
return 10 * (n % 10) + n / 10;
}
The way to build on that would be to extract every pair of digits from the original number, working recursively. The following deals with numbers that are an even number of digits long:
public int swapDigits(int n) {
if (n == 0) {
return 0;
return 100 * swapDigits(n / 100) + swapDigitsLessThan100(n % 100);
}
With this code, if n is an odd number of digits, the result will be to use a leading 0 as an additional digit.

Related

Rounding integers to one significant digit

I want to round down an int in Java, what i mean is, if I have an int 45678, i want to convert that int into 40000
this is how im calling it
int den = placeValue(startCode,length);
and this is the code
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
so if i have 89765, i would want 80000,
but instead it return the place value of whatever length is.
So,
for 89765, the length would be 5, so the return value is 5 i.e. the value in the ones place.
but if the number was 85760
then it would return 5000.
I hope that makes sense.
Any suggestions would be much appreicated.
In my opinions, if I can avoid 'calculating' I will compute the answer from other concept since I am not confidence on my math (haha).
Here is my answer. (only work in positive numbers)
I think the length of the inputted number is not necessary.
static int placeValue2(int N) {
String tar = N+"";
String rtn = tar.substring(0,1); // take first digital
for (int i=0;i<tar.length()-1;i++) // pad following digitals
rtn+="0";
return Integer.parseInt(rtn);
}
I appreciate you asked the question here.
Here is my solution. I don't know why you are taking two parameters, but I tried it from one param.
class PlaceValue{
int placeValue(int num){
int length = 0; int temp2=1;
boolean result=false;
long temp1=1;
if (num<0){
result=true;
num=num*(-1);
}
if (num==0){
System.out.println("Value 0 not allowed");
return 0;
}
while (temp1 <= num){ //This loop checks for the length, multiplying temp1 with 10
//untill its <= number. length++ counts the length.
length++;
temp1*=10;
}
for (int i=1; i<length; i++){//this loop multiplies temp2 with 10 length number times.
// like if length 2 then 100. if 5 then 10000
temp2=temp2*10;
}
temp2=(num/temp2)*temp2;
/* Let's say number is 2345. This would divide it over 1000, giving us 2;
in the same line multiplying it with the temp2 which is same 1000 resulting 2000.
now 2345 became 2000;
*/
if (result==true){
temp2=temp2*(-1);
}
return temp2;
}
}
Here is the code above. You can try this. If you are dealing with the long numbers, go for long in function type as well as the variable being returned and in the main function. I hope you understand. otherwise, ask me.
Do you want something like this?
public static int roundDown(int number, int magnitude) {
int mag = (int) Math.pow(10, magnitude);
return (number / mag) * mag;
}
roundDown(53278,4) -> 50000
roundDown(46287,3) -> 46000
roundDown(65478,2) -> 65400
roundDown(43298,1) -> 43290
roundDown(43278,0) -> 43278
So the equivalent that will only use the most significant digit is:
public static int roundDown(int number) {
int zeros = (int) Math.log10(number);
int mag = (int) Math.pow(10, zeros);
return (number / mag) * mag;
}

Program to sum the odd digits recursively

Using recursion, If n is 123, the code should return 4 (i.e. 1+3). But instead it is returning the last digit, in this case 3.
public static int sumOfOddDigits(NaturalNumber n) {
int ans = 0;
if (!n.isZero()) {
int r = n.divideBy10();
sumOfOddDigits(n);
if (r % 2 != 0) {
ans = ans + r;
}
n.multiplyBy10(r);
}
return ans;
}
It isn't clear what NaturalNumber is or why you would prefer it to int, but your algorithm is easy enough to follow with int (and off). First, you want the remainder (or modulus) of division by 10. That is the far right digit. Determine if it is odd. If it is add it to the answer, and then when you recurse divide by 10 and make sure to add the result to the answer. Like,
public static int sumOfOddDigits(int n) {
int ans = 0;
if (n != 0) {
int r = n % 10;
if (r % 2 != 0) {
ans += r;
}
ans += sumOfOddDigits(n / 10);
}
return ans;
}
One problem is that you’re calling multiplyBy on n and not doing anything with the result. NaturalNumber seems likely to be immutable, so the method call has no effect.
But using recursion lets you write declarative code, this kind of imperative logic isn’t needed. instead of mutating local variables you can use the argument list to hold the values to be used in the next iteration:
public static int sumOfOddDigits(final int n) {
return sumOfOddDigits(n, 0);
}
// overload to pass in running total as an argument
public static int sumOfOddDigits(final int n, final int total) {
// base case: no digits left
if (n == 0)
return total;
// n is even: check other digits of n
if (n % 2 == 0)
return sumOfOddDigits(n / 10, total);
// n is odd: add last digit to total,
// then check other digits of n
return sumOfOddDigits(n / 10, n % 10 + total);
}

How to calculate the number of zeros in binary?

Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you!
My code is Below:
public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
m = m / 2.0;
if (m == Math.floor(m)) {
zeroCount++;
} else {
m = Math.floor(m);
}
}
return zeroCount;
}
Below is a more concise way to solve this problem
public static int binaryZeros(int n) {
int zeroCount = 0;
// Run a while loop until n is greater than or equals to 1
while(n >= 1)
{
/* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2).
Keep in mind that binary representation is an array of these reminders until the number is equal to 1.
And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/
if(n % 2 == 0)
{
zeroCount++;
}
n = n / 2;
}
return zeroCount;
}
Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String.
Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:
public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
if(binaryString.charAt[i].equals('0')
zeros++;
return zeros;
}
I believe this would be a simpler option and it doesn't have any errors.
Once m == 0.0, it will never change, so your while loop will never stop.
If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m > 0.0).
Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:
static int binaryZeros(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}
Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.
~ complements the bits
&1 masks the low order bit. Is either 1 or 0
>>> shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")");
System.out.println(binaryZeros(-44) + " ("Integer.toBinaryString(-44)+")");
public static int binaryZeros(int v) {
int count = 0;
while (v != 0) {
// count 1 bits
// of ~v
count += (~v)&1;
v >>>=1;
}
return count;
}
Prints
3 (101100)
4 (11111111111111111111111111010100)
Just be simple, whe there's Integer.bitCount(n) method:
public static int binaryZeros(int n) {
long val = n & 0xFFFFFFFFL;
int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
int setBits = Long.bitCount(val);
return totalBits - setBits;
}
public static int getZeros(int num) {
String str= Integer.toBinaryString(num);
int count=0;
for(int i=0; i<str.length(); i++) {
if(str.charAt(i)=='0') count++;
}
return count;
}
The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.

Return the count how many digits are 7 in the given number n

I'm writing a method for my CS151 class called countSevens(n). It Returns count how many digits are 7 in the given number n. This is what I have so far but I'm doing something wrong that I can't figure out.
public int countSevens(int n){
int count = 0;
String strI = Integer.toString(n);
for (int i = 0; i < strI.length(); i++){
if(strI.substring(i).equals("7")){
count++;
}
}
return count;
}
You can do it with java streams
public int countSevens(int n) {
return (int) String.valueOf(n).chars().filter(ch -> ch == '7').count();
}
(int) - cast to an int type, in this particular case it safe to cast long to int, because we can't get a conversation error. In other cases it's better to use Math.toIntExact(long)
String.valueOf(n) - convert to string
chars() - return stream of chars
filter(ch -> ch == '7') - filter all chars that equals to 7
count() - returns the count of elements in this stream
strI.substring(i)
Will return the part of string from i-character to the end.
Use strI.charAt(i) instead
From the definition of String.substring(int):
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.
So this will only count the last instance of a 7 in your number, and only if it's the last digit in the number.
Instead, try this:
if(strI.substring(i, i+1).equals("7"))
Or, since you're dealing with ints, you can avoid using strings altogether. n % 10 will get you the last digit, and n /= 10 will bump the entire number right by one digit. That should be enough to get you started on doing this without Strings.
To count the number of 7s in an integer:
int counter = 0;
int number = 237123;
String str_number = String.valueOf(number);
for(char c : str_number.toCharArray()){
if(c == '7'){
counter++;
}
}
You can just use simple arithmetics:
public static int countSevens(int i) {
int count = 0;
for (i = i < 0 ? -i : i; i != 0; count += i % 10 == 7 ? 1 : 0, i /= 10);
return count;
}
But who can read this? Not many, so here is a cleaner solution, applying the same logic:
public static int countSevens(int i) {
int count = 0;
// ignore negative numbers
i = Math.abs(i);
while(i != 0) {
// if last digit is a 7
if(i % 10 == 7) {
// then increase the counter
count++;
}
// remove the last digit
i /= 10;
}
return count;
}

How do I use a recursion for sum of squares from user input?

Let's say for the user input 1, I can easily find the square of it. (A single digit input)
How do I use a recursive method to find the sum of squares (input with more than one number) e.g. 12345 should give 1*1 + 2*2 + 3*3 + 4*4 + 5*5 = 55? For the base case, it is correct to as num == 1 right? And from there, how do I compute the subsequent number behind 1?
public static int squareSum(int num) {
if (num == 1) {
return num*num;
} else {
return 0;
}
}
You have to think about the small steps first. It is all about extracting the digits and the calculating the squares.
public static int squareSum(int num) {
if (num == 0) return 0;
return (num%10)*(num%10) + squareSum(num/10);
}
For 12345 :-
f(12345)
f(1234)+5*5
f(123)+4*4+5*5
f(12)+3*3+4*4+5*5
f(1)+2*2+3*3+4*4+5*5
f(0)+1*1+2*2+3*3+4*4+5*5
The problem is, that you can't get the number at position x easily. The fact that 12345 consists of the numbers 1, 2, ... is only obvious in the decimal system. We will therefore store our number as a String, take each character and parse it to an integer. Then we square the number and add them
int i sum = 0;
String iAsString = i;
for (int i = 0; i < iAsString.length; i++) {
int currentNumber = Character.getNumericValue(iAsString.charAt(i));
sum += currentNumber * currentNumber;
}

Categories

Resources