I am creating a method that needs to read a 5 digit integer digit by digit. (ie 26505 would be read as 2 6 5 0 5, and each digit could be read individually in another method) I cannot convert the integer to a string and read each character because I need the digits to be read by another method. It has also been suggested to use %10 but that wouldnt give me individual digits. Also, the integer needs to be read digit by digit from the left to right. I hope this is clear enough, but I am really confused on how to complete this and everything I have tried does not work. Any help offered would be appreciated, thank you.
while(d>=10){
j=code%d;
d=d/10;
printDigit(j)
This will return an array with the integer digits in order.
public static int[] integerToDigits(int n)
{
int[] digits= new int[5];
int temp = n;
for(int i = 0; i < 5; i++)
{
digits[4-i] = temp % 10;
temp /= 10;
}
return digits;
}
integerToDigits(12345) = {1,2,3,4,5}
For getting single digits from left-to-right: -
26505 / 10000 = 2
26505 % 10000 = 6505
6505 / 1000 = 6
6505 % 1000 = 505
505 / 100 = 5
505 % 100 = 5
5 / 10 = 5
I think you can now implement it.
But, if you are OK with traversing from right-to-left, it would be easier, since then your denominator will be fixed to 10: -
26505 % 10 = 5
26505 / 10 = 2650
2650 % 10 = 0
2650 / 10 = 265
265 % 10 = 5
265 / 10 = 26
26 % 10 = 6
26 / 10 = 2
2 % 10 = 2
Something totally lazy would look like
final int [] digits = {score % 1000 / 100, score % 100 / 10, score % 10};
which would work if you know your ints will never be larger than 999, for example.
From this example, it is trivial to improve it to support arbitrary integers by calculating the next power of ten from your integer and then adding digits to the array in a loop.
You can do this:
you can create a integer array and parse the each character of the user input string into and store into an array
then you can use this array for your other method.
e.g.
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
int[] digitArray = new int[str.length()];
for(int i=0; i<str.length(); i++)
{
String temp = Character.toString(str.charAt(i));
System.out.println("temp is "+temp);
digitArray[i] = Integer.parseInt(temp);
}
for (int i =0; i<digitArray.length; i++) {
System.out.println(digitArray[i]);
}
Related
Problem statement: Three digit sum - Find all the numbers between 1 and 999 where the sum of the 1st digit and the 2nd digit is equal to the 3rd digit.
Examples:
123 : 1+2 = 3
246 : 2+4 = 6
Java:
public class AssignmentFive {
public static void main(String[] args) {
int i=1;
int valuetwo;
int n=1;
int sum = 0;
int valuethree;
int valueone = 0;
String Numbers = "";
for (i = 1; i <= 999; i++) {
n = i;
while (n > 1) {
valueone = n % 10;/*To get the ones place digit*/
n = n / 10;
valuetwo = n % 10;/*To get the tens place digit*/
n = n / 10;
valuethree = n;/*To get the hundreds place digit*/
sum = valuethree + valuetwo;/*adding the hundreds place and
tens place*/
}
/*Checking if the ones place digit is equal to the sum and then print
the values in a string format*/
if (sum == valueone) {
Numbers = Numbers + n + " ";
System.out.println(Numbers);
}
}
}
}
I got my result :
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000001
100000000011
1000000000111
10000000001111
100000000011111
1000000000111111
10000000001111111
100000000011111111
1000000000111111111
Process finished with exit code 0
The result is not showing the actual result like it should be which should show values like: 123, 246 (Please refer to the problem statement above.)
Please let me know what seems to be the issue with the code and how to tweak it.
Don't know what you're trying to do with that while loop, or why you are building up a space-separated string of numbers.
Your code should be something like:
for (int n = 1; n <= 999; n++) {
int digit1 = // for you to write code here
int digit2 = // for you to write code here
int digit3 = // for you to write code here
if (digit1 + digit2 == digit3) {
// print n here
}
}
So basically your question is how to calculate the numbers, right?
My first hint for you would be how to get the first, second and third value from a 2 or 3 digit number.
For example for 3 digits you can do int hundretDigit = (n - (n % 100)) % 100. Of course this is really inefficient. But just get code working before optimizing it ;)
Just think about a way to get the "ten-digit" (2nd number). Then you add them and if they equal the third one you write System.out.println(<number>);
EDIT:
For 2 digit numbers I will give you the code:
if(i >= 10 && i <= 99) {
int leftDigit = (i - (i % 10)) / 10;
if(leftDigit == (i % 10)) {
//Left digit equals right digit (for example 33 => 3 = 3
System.out.println(i);
}
}
Try again and edit your source code. If you have more questions I will edit my (this) answer to give you a little bit more help if you need!
This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 3 years ago.
I'm a Java beginner so please pardon me if the question seems silly but I already searched the forums but it seems like no one has my problem.
I need to reverse the digits of an integer, and my class hasn't covered while or if loops yet, so I can't use those. All answers I can find on stackoverflow use those, so I can't use those.
the input I am given is below 10000 and above 0 and the code I have written has no problem reversing the integer if the input is 4 digits (e.g. 1000 - 9999) but once the input is between 1 - 999 it creates zeroes on the right hand side but according to the answer sheets its wrong.
For example: 1534 gets turned into 4351, but
403 becomes 3040 instead of the 304 it should be, and 4 becomes 4000 instead of 4.
I've tried different things in the code but it seems to just keep giving the same answer. Or maybe I'm just missing some key mathematics, I'm not sure.
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
value = (value / 10);
int digit2 = (value % 10);
value = (value / 10);
int digit3 = (value % 10);
value = (value / 10);
int digit4 = (value % 10);
String reversednum = ("" + digit + digit2 + digit3 + digit4);
System.out.println ( reversednum);
and
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
int reversednum = (digit);
value = (value /10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value);
reversednum = (reversednum * 10 + digit);
System.out.println (reversednum);
What am I doing wrong?
You can convert from int to String -> reverse String -> convert again in int.
This is a code example.
public int getReverseInt(int value) {
String revertedStr = new StringBuilder(value).reverse().toString();
return Integer.parseInt(revertedStr);
}
Your code assumes that the number can be divided by 1000, which is clearly not the case for numbers below 1000. So add some if statements:
public int reverseNumber(int n) {
// step one: we find the factors using integer maths
int s = n;
int thousands = s / 1000; // this will be 0 if the number is <1000
s = s - thousands*1000;
int hundreds = s / 100; // this will be 0 if the number is <100
s = s - hundreds*100;
int tens = s / 10; // etc.
s = s - tens*10;
int ones = s;
// then: let's start reversing. single digit?
if (n<10) return n;
// two digits?
if (n<100) {
return ones*10 + tens;
}
// etc.
if (n<1000) {
return ones*100 + tens*10 + hundreds;
}
if (n<10000) {
return ones*1000 + tens*100 + hundreds*10 + thousands;
}
// if we get here, we have no idea what to do with this number.
return n;
}
Without spoon-feeding you code (leaving the value of writing your own homework code intact)...
Although you've said you can't use a loop, I don't think there's a sane approach that doesn't use one. Your basic problem is you have hard-coded a solution that works when the number happens to have 4 digits, rather than using code that adapts to a variable length. ie, are not using a loop.
All is not lost with your code however. You have figured out the essence of the solution. You just need to convert it to work processing one digit at a time. Consider using recursion, that divides the number by 10 each time and continues until the number is zero. Of course, you’ll have to capture the end digit before it’s lost by division.
Pseudo code may look like:
pass in the number and the current result
if the number is 0 return result
multiply result by 10 and add remainder of number divided by 10
return the result of calling self with number divided by 10 and result
then call this passing number and zero
Using modulus and division:
int nbr = 123; // reverse to 321 or 3*10*10 + 2*10 + 1
int rev = 0;
while(nbr > 0) {
rev *= 10; // shift left 1 digit
int temp = nbr % 10; // get LO digit
rev += temp; // add in next digit
nbr /= 10; // move to next digit
}
Or a recursive method:
public static int reverseInt(int number, int value) {
switch(number) { // is this conditional statement allowed???
case 0:
return value;
}
value *= 10;
int lod = number % 10;
value += lod;
number /= 10;
return reverseInt(number, value);
}
For school, i've got an assignment to encrypt a four-digit Integer by the following requirements.
A company wants to transmit data over the telephone, but they are
concerned that their phones may be tapped. All of their data is
transmitted as four-digit integers. They have asked you to write a
method that will encrypt their data so that it may be transmitted more
securely. Your method should read a four-digit integer and encrypt it
as follows: Replace each digit by (the sum of that digit plus 7)
modulus 10. Then, swap the second digit with the fourth. Then print
the encrypted integer. Write a separate method that inputs an
en-crypted four-digit integer, and decrypts it to form the original
number.
The encrypting of the four-digit wasn't such of a problem, I've converted it to a string, then to a char array and then seperately encrypted the numbers by its needs.
The method I made looks like this:
public int encrypt4DigitNumber(int number) throws Exception {
String numberAsString = String.valueOf(number);
if (numberAsString.length() != 4) {
throw new Exception("The digit has to be 4 digits long");
}
int[] numbers = new int[4];
char[] numbersAsChars = numberAsString.toCharArray();
for (int index = 0; index < numbersAsChars.length; index++) {
int currentNumber = Character.getNumericValue(numbersAsChars[index]);
int numberToReplace = (currentNumber + 7) % 10;
numbers[index] = numberToReplace;
}
int second = numbers[1];
int fourth = numbers[3];
numbers[1] = fourth;
numbers[3] = second;
StringBuilder encryptedNumberStringBuilder = new StringBuilder();
for (int encryptedNumber : numbers) {
encryptedNumberStringBuilder.append(encryptedNumber);
}
String encryptedNumberString = encryptedNumberStringBuilder.toString();
return Integer.parseInt(encryptedNumberString);
}
The problem came when I had to de-crypt the encrypted four-digit code.
I know I had to swap the 2 array elements, and add 7 to each number in the array.
The thing I didn't know how to do was reverse the modulus operator, the only thing I can come up with is multiply the current number by 10, but that won't work.
After doing some research, I have to search the left-overs from the modulus somewhere, but I have absolutely no idea how to do that. Do I need to return those in the encrypt function aswell and pass them into the decrypt function?
Can someone explain the process of reversing the modulus operator?
If you encrypt a number from 0 to 9 (= mod 10) with an offset 7, you can of course subtract the offset from every digit during decryption and wrap around if the number is negative, but that is not very nice:
int numberToReplace = currentNumber - 7;
if (numberToReplace < 0) {
numberToReplace += 10;
}
If the encryption offset is 7, then the decryption offset would be 3 (10 - 7). You could just add 3 to each digit and apply mod 10 in order to decrypt them.
int numberToReplace = (currentNumber + 3) % 10;
Let's see what actually (i + 7) % 10 do:
0 = 7
1 = 8
2 = 9
3 = 0
4 = 1
5 = 2
6 = 3
7 = 4
8 = 5
9 = 6
As you can see there's definitely quite obvious pattern. So in order to decode our original digit back we have to do
(i + 3) % 10
I'm trying to create a method to validate a credit card number, but we have to process it as a string
heres some information about my task...
Credit card numbers follow certain patterns. A credit card must have between 13 and 16 digits.
In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is useful to determine if a card number is entered correctly or if a credit card is scanned correctly by a scanner. Almost all credit card numbers are generated following this validity check, commonly know as the Luhn check or the Modulus 10 check, which can be described as follows. For illustration, consider the card number 4388576018402625.
Double every second digit from right to left. If doubling of a digit results in a 2-digit number, add up the two digits to get a single-digit number.
2 x 2 = 4
2 x 2 = 4
4 x 2 = 8
1 x 2 = 2
6 x 2 = 12 (1+2= 3)
5 x 2 = 10 (1+0= 1)
8 x 2 = 16 (1+6= 7)
4 x 2 = 8
Add all the single digit numbers from step 1 4 + 4 +8 + 2 +3 + 1 + 7 + 8 = 37
Add all digits in the odd places from right to left in the card number
5 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 37
Sum the results from step 2 and step 3 37 + 37 = 74
If the result from step is divisible by 10, the card number is valid; otherwise, it’s invalid. For example, the number 4388576018402625 is invalid, but the number 4388576018410707 is a valid Visa card; the number 6011000593748745 is invalid, but the number 6011000593748746 is a valid Discover card.
here's what I have so far
static void CreditCardValidator() {
System.out.println("enter a credit card number");
String temp = options.nextLine();
if (temp.length() < 13 || temp.length() > 16) {
System.out.println("Input is invalid");
}
// inside loop with char at command do all the math
int tmpdouble;
int sum = 0;
int counter = temp.length() - 1;
for (int i = temp.length(); i != 0; i--) {
char tmp = temp.charAt(i);
//tmp converted to int
tmpdouble = tmp * 2;
int firstDigit;
int secondDigit;
if (tmpdouble >= 10) {
firstDigit = i / 10;
secondDigit = i % 10;
sum = sum + firstDigit + secondDigit;
}
else if(tmpdouble <= 9) {
sum = sum + tmpdouble;
}
HELP HERE{
// need to have it do the same thing as above but for odd numbers
}
where do I go from there? ^^
Thanks
Don't roll your own. This algorithm is already provided via commons.
https://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/CreditCardValidator.html
I've been experiencing occasional lags in my Android game when the garbage collector runs. I ran DDMS and discovered that all of the memory being allocated by my application is from this line:
scoreString = String.valueOf(score);
What is the best way to convert an integer to a string without allocating any memory?
Allocate an array of characters to be displayed as the score, and use a lookup table of 0-9 (this conveniently maps to a 0-base array anyway) to append to this array based on each digit of the score.
Edit:
To extract the digits from your score:
12345 mod 10 = 5
12345 mod 100 = 45 / 10 = 4.5 (floors to 4)
12345 mod 1000 = 345 / 100 = 3.45 (floors to 3)
12345 mod 10000 = 2345 / 1000 = 2.345 (floors to 2)
12345 mod 100000 = 12345 / 10000 = 1.2345 (floors to 1)
Also you'll know what the max length for the score character array should be based on whatever you're using to store score (i.e. int)
I recommend reverse-filling this array and initializing it to all '0' so your score will display like
0000000000
0000005127
I just ran into this problem also, if the GC kicks in during a frame it's really noticeble. I came up with this solution.
If you fill the buffer backwards, you can just repeatedly % 10 and / 10.
A working implementation that appends a number to a StringBuilder, probably not the best way to do it but it works and causes no allocations. You could also use another character array for the values instead of casting to char and adding 48 ('0' in ascii)
private char[] sbBuffer = new char[20];
private void appendInt(StringBuilder sb, int num) {
int i,j;
i = sbBuffer.length - 1;
if (num == 0) {
j = sbBuffer.length - 1;
sbBuffer[j] = (char) 48;
} else {
if (num < 0)
sb.append('-');
num = Math.abs(num);
while (num > 0) {
sbBuffer[i] = (char) (num % 10 + 48);
i--;
num /= 10;
}
j = i + 1;
}
sb.append(sbBuffer, j, sbBuffer.length - j);
/* clean up */
for (i = j; i < sbBuffer.length; i++)
sbBuffer[i] = 0;
}