I'm trying to declare a method for my program that takes only a 5 digit integer and for each digit of the integer, reads a value from the program and prints it out. I understand this isn't very clear but im having trouble relaying what I mean. I understand it will be some sort of for loop to read each digit of the integer individually until something reaches 5. Something like the charAt() string method but works for digits.
Read up on "modulo". It is a primitive operation, available via the symbol % in Java.
For division, it is the remainder. So
System.out.println("Last digit: "+(12345 % 10));
will print 5. Figure out yourself how to get the other digits.
As an exercise, figure out how to print binary digits.
You can divide and take modulo.
while(n > 0) {
System.out.println("Digit " + (n % 10));
n /= 10;
}
This works fine if you are using any base: all you need to do is substitute 10 for the base (dividing by the base means shifting everything left, and taking the modulo means getting the last digit).
You can very easily convert your integer to a string and use charAt()
String parseableString = Integer.toString(yourInt);
for (int i = 0; i < parseableString.length(); i++){
System.out.println(parseableString.charAt(i));
}
Related
I am new to Java and programming all together.. I am trying to make a program that ciphers a number for the user. The user inputs 5 digits separately so I add them together to get a total. I need to pull the first digit and second digit of the total and enter it into (firstDigit+key)%10 and (secondDigit+key)%10. Then need to combine the answer to each equation together.
My total needs to be two digits, so even if the user enters all 1's which would total to be 5, I need it to be displayed and seen as 05 so that both equations have a digit to use. It needs to be two digits. I cant seem to figure how to enter a place holder. I was thinking about trying to use:
if (total < 10)
but then what?
Secondly, the method I used below seems like a terrible way to pull a single digit from a number. I think I changed the int total into a string so I can use .substring to pull the digits, then converted back to an int. Surprisingly it works. Is there a better way to do this knowing that the number is random?
String totalString = Integer.toString(total);
String stringDigit1 = totalString.substring(0,1);
String stringDigit2 = totalString.substring(1,2);
int firstDigitInt1 = Integer.parseInt(stringDigit1);
int firstDigitInt2 = Integer.parseInt(stringDigit2);
int encodedDigit1 = (firstDigitInt1+key)%10;
int encodedDigit2 = (firstDigitInt2+key)%10;
System.out.println("Your encoded Number is: " + encodedDigit1 + encodedDigit2);
Your method for obtaining the individual digits is good, and if you want to maintain it I believe your intuition is correct, it should suffice to say:
if (total < 10) {
firstDigitInt1 = 0
}
This will work out with your following math.
Your method with substrings is far from terrible, but in case you wanted something more sleek you can instead say:
int Digit1 = total / 10;
int Digit2 = total % 10;
Here, you can take advantage of integer truncation (where an integer won't remember decimal places) to get the first digit, which also solves the first problem: 5 / 10 = 0 (in terms of ints). For the second digit, it suffices to say modulo 10, as it is the remainder once the total is divided by 10.
I would like some help with my code. I'm doing a method to convert binary numbers to decimals. This is my code:
public double decimal(double number){
String num=(number+"");
char charac;
double n;
double cont=0;
double exp;
double res=0;
for(int i=num.length()-1;i>=0;i--){
charac=num.charAt(i);//obtains digits 1 by 1 and converts to char
n=(Character)charac;//converts the digit into a number (double)
exp=Math.pow(2, cont);//makes the exponential function to multiply to n
n=n*exp;//multiplies exponential with the digit
res+=n;//adds digit to accumulator
cont++;
}
return res;
}
the problem i'm having is that the numbers get all messed up for whatever reason, like n being assigned 48 in the first loop of the for cycle.
I tried using n as an Int instead and it seemed to be working well but at the second loop of the for cycle it was assigned -2 somehow and that ruined the addition.
Change
n=(Character)charac;
to use Character.digit(char, int) otherwise you get the ascii value (not the digit value)
n=Character.digit(charac, 10);
By assigning char to double, it is infact passing on the ASCII value of that digit e.g. 48 is returned for char 0.
I think this answer from How to convert binary string value to decimal will help you:
String c = "110010"; // as binary
int decimalValue = Integer.parseInt(c, 2);
System.out.println(decimalValue);
result: 50
Sorry for a possible duplicate post, I saw many similar topics here but none was exactly I needed. Before actually posting a question I want to explicitly state that this question is NOT A HOMEWORK.
So the question is: how to convert a large integer number into binary representation? The integer number is large enough to fit in primitive type (Java long cannot be used). An input might be represented as a string format or as an array of digits. Disclaimer, This is not going to be a solution of production level, so I don't want to use BigInteger class. Instead, I want to implement an algorithm.
So far I ended up with the following approach:
Input and output values represented as strings. If the last digit of input is even, I prepend the output with "0", otherwise - with "1". After that, I replace input with input divided by 2. I use another method - divideByTwo for an arithmetical division. This process runs in a loop until input becomes "0" or "1". Finally, I prepend input to the output. Here's the code:
Helper Method
/**
* #param s input integer value in string representation
* #return the input divided by 2 in string representation
**/
static String divideByTwo(String s)
{
String result = "";
int dividend = 0;
int quotent = 0;
boolean dividendIsZero = false;
while (s.length() > 0)
{
int i = 1;
dividend = Character.getNumericValue(s.charAt(0));
while (dividend < 2 && i < s.length())
{
if (dividendIsZero) {result += "0";}
dividend = Integer.parseInt(s.substring(0, ++i));
}
quotent = dividend / 2;
dividend -= quotent * 2;
dividendIsZero = (dividend == 0);
result += Integer.toString(quotent);
s = s.substring(i);
if (!dividendIsZero && s.length() != 0)
{
s = Integer.toString(dividend) + s;
}
}
return result;
}
Main Method
/**
* #param s the integer in string representation
* #return the binary integer in string representation
**/
static String integerToBinary(String s)
{
if (!s.matches("[0-9]+"))
{
throw new IllegalArgumentException(s + " cannot be converted to integer");
}
String result = "";
while (!s.equals("0") && !s.equals("1"))
{
int lastDigit = Character.getNumericValue(s.charAt(s.length()-1));
result = lastDigit % 2 + result; //if last digit is even prepend 0, otherwise 1
s = divideByTwo(s);
}
return (s + result).replaceAll("^0*", "");
}
As you can see, the runtime is O(n^2). O(n) for integerToBinary method and O(n) for divideByTwo that runs inside the loop. Is there a way to achieve a better runtime? Thanks in advance!
Try this:
new BigDecimal("12345678901234567890123456789012345678901234567890").toString(2);
Edit:
For making a big-number class, you may want to have a look at my post about this a week ago. Ah, the question was by you, never mind.
The conversion between different number systems in principle is a repeated "division, remainder, multiply, add" operation. Let's look at an example:
We want to convert 123 from decimal to a base 3 number. What do we do?
Take the remainder modulo 3 - prepend this digit to the result.
Divide by 3.
If the number is bigger than 0, continue with this number at step 1
So it looks like this:
123 % 3 == 0. ==> The last digit is 0.
123 / 3 == 41.
41 % 3 == 2 ==> The second last digit is 2.
41 / 3 == 13
13 % 3 == 1 ==> The third digit is 1.
13 / 3 == 4
4 % 3 == 1 ==> The fourth digit is 1 again.
4 / 3 == 1
1 % 3 == 1 ==> The fifth digit is 1.
So, we have 11120 as the result.
The problem is that for this you need to have already some kind of division by 3 in decimal format, which is usually not the case if you don't implement your number in a decimal-based format (like I did in the answer to your last question linked above).
But it works for converting from your internal number format to any external format.
So, let's look at how we would do the inverse calculation, from 11120 (base 3) to its decimal equivalent. (Base 3 is here the placeholder for an arbitrary radix, Base 10 the placeholder for your internal radix.) In principle, this number can be written as this:
1 * 3^4 + 1 * 3^3 + 1*3^2 + 2*3^1 + 0*3^0
A better way (faster to calculate) is this:
((((1 * 3) + 1 )*3 + 1 )*3 + 2)*3 + 0
1
3
4
12
13
39
41
123
123
(This is known as Horner scheme, normally used for calculating values of polynomials.)
You can implement this in the number scheme you are implementing, if you know how to represent the input radix (and the digits) in your target system.
(I just added such a calculation to my DecimalBigInt class, but you may want to do the calculations directly in your internal data structure instead of creating a new object (or even two) of your BigNumber class for every decimal digit to be input.)
Among the simple methods there are two possible approaches (all numbers that appear here decimal)
work in decimal and divide by 2 in each step as you outlined in the question
work in binary and multiply by 10 in each step for example 123 = ((1 * 10) + 2) * 10 + 3
If you are working on a binary computer the approach 2 may be easier.
See for example this post for a more in-depth discussion of the topic.
In wikipedia, it is said:
For very large numbers, these simple methods are inefficient because
they perform a large number of multiplications or divisions where one
operand is very large. A simple divide-and-conquer algorithm is more
effective asymptotically: given a binary number, it is divided by
10^k, where k is chosen so that the quotient roughly equals the
remainder; then each of these pieces is converted to decimal and the
two are concatenated. Given a decimal number, it can be split into two
pieces of about the same size, each of which is converted to binary,
whereupon the first converted piece is multiplied by 10^k and added to
the second converted piece, where k is the number of decimal digits in
the second, least-significant piece before conversion.
I have tried, this method is faster than conventional one for numbers larger than 10,000 digits.
I want to send in the recursion only the number itself and not more variables!!!
so, I made a code that make the operation but I don't have the stop point.
the code:
public static int upsideDown (int number) {
number += (number%10)*(Math.pow(10, String.valueOf(number).length()));
number %= 10;
return upsideDown (number);
}
You need to store the digit you are working with in a local variable instead of modifying number.
You need - instead of number %= 10 - to (integer) divide by 10 instead.
You need to multiply the previously stored digit by 10 raised to the power of string.length - 1; you need to add the result of this to the return value of the recursive call to upsideDown.
Actually, a for loop over length - 1, multiplying by 10 each time through the loop would be more efficient than using pow.
Exit code should simply be if (number == 0) return 0; at start of method.
I want to generate a random number of 14 positive digits only and I use the below function for it:
public void random()
{
Random number = new Random();
long l = number.nextLong();
number.setSeed(System.currentTimeMillis());
long num = Math.abs(number.nextInt())%999 + (l/100000); // problematic line
mTextBox.setString("" + num);
}
I very new to to JavaMe, I have made above function myself but I believe it is not working as expected. It also generates -ve numbers. Also sometimes one or two digits are missing in generated number resulting in 12 or 13 numbers not 14.
Any suggestions or improvement to the code will be highly appreciated.
If you want 14 digits, then you should use 14 calls to number.nextInt(10) - something like this:
public static String randomDigits(Random random, int length)
{
char[] digits = new char[length];
// Make sure the leading digit isn't 0.
digits[0] = (char)('1' + random.nextInt(9);
for (int i = 1; i < length; i++)
{
digits[i] = (char)('0' + random.nextInt(10));
}
return new String(digits);
}
Note that I've made the instance of Random something you pass in, rather than created by the method - this makes it easier to use one instance and avoid duplicate seeding. It's also more general purpose, as it separates the "use the string in the UI" aspect from the "generate a random string of digits".
I don't know whether Random.nextInt(int) is supported on J2ME - let me know if it's not. Using Math.abs(number.nextInt())%999 is a bad idea in terms of random distributions.
I didn't understand what you really want, the code suggests that you want a 3 digit number (%999).
Otherwise you can create a 14 digit number between 1000000000000000 and 9999999999999999 by
long num = 1000000000000000L + (long)(number.nextDouble() * 8999999999999999.0);
note (1 / 100000) is 0 (zero) since it is done by integer division, use (1.0 / 100000.0) for double division
long num = 10000000000000L+(long)(random.nextDouble()*90000000000000.0);
EDIT:
mTextBox.setString(MessageFormat.format("{0,number,00000000000000}",
new Object[] {new Long(num)}));
You are getting negative numbers because Random.nextInt() returns any 32-bit integer, and half of them are negative. If you want to get only positive numbers, you should use the expression Random.nextInt() & 0x7fffffff or simply Random.nextInt(10) for a digit.