I am trying to practice java over the summer and i'm stuck on this problem. I need to swap the 2 letters in a integer in java. For example in my main method I make a method called swapdigits and have my parameters as 1432. The program should swap the 4 and 1 and 3 and 2. The output should be 4123 since it swapped the two letters in order. Lets say I do swapdigits(1341234) the output should be 3114324. I know I have to use while loops but i'm getting stuck on the swapping.
This is what I have so far:
public static void main(String[] args) {
Swapdigits(2413);
}
public static void Swapdigits(int number){
while(number>0){
int y=number/1000;
int x=number%10;
int original=number-y;
System.out.println(original);
}
System.out.println();
}
}
public static int swapDigitPairs(int number) {
int result = 0;
int place = 1;
while (number > 9) {
result += place * 10 * (number % 10);
number /= 10;
result += place * (number % 10);
number /= 10;
place *= 100;
}
return result + place * number;
}
You can also try
char[] a = String.valueOf(number).toCharArray();
for (int i = 0; i < a.length - 1; i += 2) {
char tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
}
int number = Integer.parseInt(new String(a));
Because you're just swapping the places of digits, it doesn't actually matter what the number is. So, it's probably easier (and makes more sense) to represent the argument as a string. That way you aren't dealing with weird modulo operators - If you were solving the problem by hand, would you actually do any math? You'd treat this problem the same whether it were numbers of a bunch of characters.
Take a look at the following question for information on swapping characters in a String:
How to swap String characters in Java?
Related
I am doing an assignment where I must use nested loops in order to add up the squares and cubes of integers from 1 to N (N being whatever the user inputs). For example, if the user input the number 5, the program is supposed to do "1²+2²+3²+4²+5²" and output the sum of those numbers, as well "1³+2³+3³+4³+5³" and output the sum of those numbers.
However, I am having trouble figuring out how to code it in a way that I receive the proper output? This is what I wrote. Scanners were already added.
int limitNum = input.nextInt();
double squareNums:
double sumofSq = 0;
double cubedNums;
double sumofCubes = 0;
for(int s = 1; s <= limitNum; s++)
{
for(int c = 1; c <= limitNum; c++)
{
cubedNums = Math.pow(c, 3);
sumofCubes = sumofCubes + cubedNums;
}
squareNums= Math.pow(s, 2);
sumofSq = sumofSq + squareNums;
}
But currently, when I run this program, the sum of the squares output correctly, but the sum of the cubes is always some big number. For example if 5 is used, sumofSq would output 55.0, but sumofCubes would output 1125.0.
There is no point using a nested loop as this would result in complexity of O(n²). A single loop would be sufficient and be in complexity class O(n).
public class Application {
public static void main(String[] args) {
var squareSum = 0d;
var cubeSum = 0d;
var upperBound = 5;
for(var i = 1; i <= upperBound; i++){
squareSum += Math.pow(i, 2);
cubeSum += Math.pow(i, 3);
}
System.out.printf("""
Sum of first n squares: %s
Sum of first n cubes: %s
""", (int)squareSum, (int)cubeSum);
}
}
In fact there is no need to loop at all => constant computation time no matter the size of the input O(1). There is a well known formula which tells you the sum of the first n squares.
n(n+1)(2n+1)
------------
6
Please see this for a proof.
The same holds true for the first n cubes.
n²(n+1)²
--------
4
Please see this for a proof.
The following program will therefore return the same result.
public class Application {
public static void main(String[] args) {
var upperBound = 5;
System.out.printf("""
Sum of first n squares: %s
Sum of first n cubes: %s
""", sumOfFirstNSquares(upperBound), sumOfFirstNCubes(upperBound));
}
public static int sumOfFirstNSquares(int n){
return (n * (n+1) * (2 * n + 1)) / 6;
}
public static int sumOfFirstNCubes(int n){
return ((n * n) * (n+1) * (n+1)) / 4;
}
}
In fact there is no need to loop at all => constant computation time no matter the size of the input O(1). There is a well known formula which tells you the sum of the first n squares.
java
I am a beginner in Java and trying to learn. I have an integer from whom I want to calculate the double of each digit and then restore the answer in the integer. I think that I have to use the for() loop and tempvalue. I have the number 1234 and I need to get 2468.
I did this and I got 1234. Can someone find the issue, I am not very good with the index concept.
public class Doublevalue {
public static void main(String[] args) {
num=1234;
for(int i=0;num<0;i++) {
int tempvalue=(num%10*2)/10;
num=tempvalue;
System.out.print(num);
}}}
Because doubling digits is only valid when every digit is less than 5, the solution can be just
num *= 2;
But if you want the treat each digit separately, you need to do something like this:
int tmp = 0;
for (int column = 1; num > 0; column *= 10) {
tmp += (num % 10) * column * 2;
num /= 10;
}
num = tmp;
See live demo.
You can do an in-place replacement of each digit, but the logic is a little more complicated.
The code you currently provided has everything right - except for what you are doing in the loop.
In your example, you are executing int tempvalue=(num%10*2)/10;. I'm pretty certain that you are not sure what you are doing. What the line is doing is getting the remainder of the number when it is divided by 10, multiplying it by 2, then dividing by then. I can't seem to understand why you are doing this, so I will provide my own solution.
public class DoubleDigits {
public static void main(String[] args) {
DoubleDigits dd = new DoubleDigits();
System.out.println(dd.doubleDigits(1234));
}
public int doubleDigits(int number) {
StringBuilder str = new StringBuilder();
String testCase = String.valueOf(number);
for(int i = 0; i < testCase.length(); i++) {
int digit = Integer.parseInt(String.valueOf(testCase.charAt(i)))*2;
str.append(digit);
}
return Integer.parseInt(str.toString());
}
}
So what's happening?
First, we convert the number to a String, so we can get each single character (as a number). The for loop will loop through every single character, and we can use a StringBuilder to append the character after it has been parsed to an int and multiplied by two.
In the above example, the program produces:
2468
When the test case is:
1234
And when the test case is:
9999
The result is:
18181818
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.
This problem has me puzzled. I tried using a loop like this: Basically I tried to get the first digit from the input and do the formula but it doesn't seem to work. It looks so simple but I can't figure it out. Could you help me? Thanks.
public static int ISBN(String ninedigitNum) {
number = 9;
while (number > 0) {
int nextDigit = ninedigitNum.substring(0,1);
...
}
Checksums (Source: Princeton University). The International Standard
Book Number (ISBN) is a 10 digit code that uniquely specifies a book.
The rightmost digit is a checksum digit which can be uniquely
determined from the other 9 digits from the condition that d1 + 2d2 +
3d3 + ... + 10d10 must be a multiple of 11 (here di denotes the ith
digit from the right). The checksum digit d1 can be any value from 0
to 10: the ISBN convention is to use the value X to denote 10.
Example: the checksum digit corresponding to 020131452 is 5 since is
the only value of d1 between 0 and and 10 for which d1 + 2*2 + 3*5 +
4*4 + 5*1 + 6*3 + 7*1 + 8*0 + 9*2 + 10*0 is a multiple of 11. Create a
Java method ISBN() that takes a 9-digit integer as input, computes the
checksum, and returns the 10-digit ISBN number. Create 3 JUnit test
cases to test your method.
I got it, thanks a lot everyone!
What about it isn't working? Either way, I believe what you're missing is that you're continually getting the same substring, which will be the first number of the string: int nextDigit = ninedigitNum.substring(0,1);. In addition, you're going to want to use an int, not a String; you can technically convert from String to int if desired, but the problem itself calls for an int.
There are two ways to do this that jump to mind. I would do this by realizing that mod in powers of 10 will give you the respective digit of an integer, but the easier way is to convert to a char array and then access directly. Note that there's no error checking here; you'll have to add that yourself. In addition, there are a LOT of 'magic numbers' here: good code typically has very, very few. I would recommend learning more data structures before attempting problems like these; to be honest there's very few things you can do without at least arrays and linked lists.
char[] ISBN = ninedigitNum.toCharArray();
//Process each number
int total = 0;
for(int i=0; i<9; i++){
int current_int = Integer.parseInt(ISBN[i]);
total += current_int * (10 - i)
}
//Find value of d1
for(int i=0; i<9; i++){
if(((total + i) % 11) == 0){
total += i*100000000;
break;
}
}
return total;
In general: Use print outs with System.out.println(x); or use your compiler's debugger to see what's going on during processing.
So,
This is the piece of code that I wrote. I still think it could be made more efficient.
public class Problem3 {
public static String ISBN(String x)
{
char[]temp = x.toCharArray();
int counter = 2;
int sum = 0;
int j=0;
for(int i=8;i>=0;i--)
{
sum+= counter*Integer.parseInt(""+temp[i]);
counter+=1;
}
for(j=0;j<10;j++)
{
if((sum+j)%11==0)
{
break;
}
}
return x+""+j;
}
public static void main(String args[])
{
String a = "020131452";
System.out.println(ISBN(a));
}
}
Hope this helps.
This works:
public static int ISBN(String nineDigitNum){
int sum = 0;
for(int i = 0; i<nineDigitNum.length(); i++){
sum += Integer.parseInt(""+nineDigitNum.charAt(i))*(10-i);
}
return (sum%11);
}
Also I believe if the checksum is == to 10, it should return an X, so you could either change the return type and add an if statement somewhere, or just put the if statement outside wherever you are using this method.
Here is a short one without loops that uses only substring(), charAt() and length():
public static String ISBN(String nineDigits) {
int chkD = 11 - checkDigit(nineDigits, 0);
return nineDigits + ((chkD == 10) ? "X" : chkD);
}
public static int checkDigit(String nDsub, int chkD) {
if (nDsub.length() == 0)
return 0;
chkD = ((nDsub.charAt(0) - '0') * (nDsub.length() + 1));
return (chkD + checkDigit(nDsub.substring(1), chkD)) % 11;
}
Output:
> ISBN("123456789")
"123456789X"
> ISBN("123456780")
"1234567806"
I want to convert decimal numbers to binary numbers. I want to store them in an array.
First I need to create an array that has a certain length so that I can store the binary numbers. After that I perform the conversion, here is how I do it:
public class Aufg3 {
public static void main(String[] args) {
int[] test = decToBin(12, getBinArray(12));
for(int i = 0; i < test.length; i++){
System.out.println(test[i]);
}
}
public static int[] getBinArray(int number){
int res = number, length = 0;
while(res != 0){
res /= 2;
length++;
}
return new int[length];
}
public static int[] decToBin(int number, int[] array){
int res = number, k = array.length-1;
while(res != 0){
if(res%2 == 0){
array[k] = 0;
}else{
array[k] = 1;
}
k--;
res /= 2;
}
return array;
}
}
Is there anything to improve? It should print 1100 for input of 12.
Why not just use the toBinaryString method of the Integer class:
System.out.println(Integer.toBinaryString(12))
I assume you want to write your own code -- otherwise this is straightforward to do using methods from the standard Java library.
Some quick comments:
You can get rid of the res temp vars. Work directly on number (remember that Java passes parameters by value).
Shift is more efficient than division (number >>>= 1 instead of number /= 2), although the compiler should be able to optimize this anyway
You can avoid the modulus in decToBin if you just do array[k] = number & 1;
While you are at it, why not call getBinArray from decToBin directly? Then you can call decToBin with only one arg -- the value to convert.
Here is a slightly optimized version of your code:
public static int[] getBinArray(int number) {
int length = 0;
while (number != 0) {
number >>>= 1;
length++;
}
return new int[length];
}
public static int[] decToBin(int number) {
int[] array = getBinArray(number);
int k = array.length-1;
while (number != 0)
{
array[k--] = number & 1;
number >>>= 1;
}
return array;
}
If this isn't homework, no need to do it yourself. The following code should work:
BigInteger bigInt = new BigInteger(number);
String asString = bigInt.toString(2);
There might be more efficient ways, but this is certainly very readable and maintainable.
There are some small things that you can improve:
You should define a "high-level" method that converts an int to an int[]. In the current code you have to mention the 12 two times, which is bad.
You should use a do { ... } while (number != 0) loop. Otherwise the number 0 will be represented by an empty array.
You should use x >>> 1 instead of x / 2, since that handles negative numbers correctly.
If you want to check that your code is correct, write another method that converts back from binary to int. Then you can check that binToDec(decToBin(12, ...)) == 12.
The method getBinArray should not be public, since it is only a helper method. You can either replace the public with private or just remove the public.