I have one integer number and my goal is, to sum up digits in that integer
I tried with charAt(); but the weird part is when I'm trying to check numbers with their
index its works well but the part I don't understand is when I'm trying to sum them up
why 2 + 2 is 100
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
String string_number = Integer.toString(number);
System.out.println(string_number.charAt(0));
System.out.println(string_number.charAt(1));
System.out.println(string_number.charAt(0) + string_number.charAt(1));
input 22
Output
2
2
100
A character in Java is close to its unicode code point. And the unicode code point of '2' is... 0x32 or 50!
And yes, 50 + 50 is 100...
Fortunately, the value of a decimal digit is guaranteed to be c - '0', so what you want is:
System.out.println((string_number.charAt(0) - '0') + (string_number.charAt(1) - '0'));
You are calculating the sum of the ASCII values of the characters.
The ASCII value of the character '2' is 50. You are therefore adding 50 and 50.
You need to convert the character to the number first.
Related
I am trying to write some text to a file using PrintWriter and I do not understand what "7" means in the next example:
double d = 12.11211;
out.format(â%7.3fâ, d);
The source from where I am inspiring says that 7 means:
The 7.3 before the f denotes the width (7) and precision (3) to output
d in.
The problem is that I cannot understand what that width really means. I mean, even though my variable would have more than 7 digits, it is not going to format anything.
Think of it as the total length of the string produced by the applied format.
If you take in account that there will be exactly 3 chars after the decimal point and 1 char for the decimal point itself, then it leaves 3 chars for the integer part.
Because your number has only 2 digits in the integer part the final result will be padded at the left with a white space:
double d = 12.11211;
out.format("%7.3f", d);
will create:
" 12.112"
with
out.format("%8.3f", d);
you get
" 12.112"
and so on.
The minimum length of the formatted string is in your case:
6 = 2 chars for the integer part + 1 char for the decimal point + 3 chars for the digits after the decimal point
so even if you set:
out.format("%5.3f", d);
this will not truncate the result, it will be:
"12.112"
For simple text arguments, you can think of the width and precision as a minimum and maximum number of characters to be output. For floating-point numeric types, the precision changes meaning slightly and controls the number of digits displayed after the decimal point.
watch this example:
System.out.printf("String is '%5s'\n", "A");
// String is ' A'
System.out.printf("String is '%.5s'\n", "Happy Birthday!");
// String is 'Happy'
for more information look at this link
Your source of inspiration should be the javadoc. It says:
The width is the minimum number of characters to be written to the
output. If the length of the converted value is less than the width
then the output will be padded by ' ' ('\u0020') until the total
number of characters equals the width. The padding is on the left by
default.[...]
For the floating-point conversions 'a', 'A', 'e', 'E', and 'f' the precision is the number of digits after the radix point.
A simple experiment shows it:
System.out.printf("%7.3f%n", 1.3);
System.out.printf("%7.3f%n", 12.3);
System.out.printf("%7.3f%n", 12.34);
System.out.printf("%7.3f%n", 12.345);
System.out.printf("%7.3f%n", 12.3456);
System.out.printf("%7.3f%n", 12.34567);
System.out.printf("%7.3f%n", 12.34567);
System.out.printf("%7.3f%n", 123.34567);
System.out.printf("%7.3f%n", 1234.34567);
System.out.printf("%7.3f%n", 12345.34567);
prints:
1,300
12,300
12,340
12,345
12,346
12,346
12,346
123,346
1234,346
12345,346
By width, it means the string will always fill the rest of the places if the number of digits/characters of the value is less than the given number.
double d = 12.11211;
String.format(â%7.3fâ, d);
> 12.112
^^^^^^^
1234567
According to this:
The field width in a formatting operator is a nonnegative integer that
specifies the number of digits or characters in the output when
formatting input values. For example, in the operator %7.3f, the field
width is 7.
By default, the output text is padded with space
characters when the field width is greater than the number of
characters.
The 7 adds padding () in case the output is smaller than 7 characters. This way the output is always at least 7 characters, with 3 floating decimals.
This documentation gives a very detailed explanation for formatting text in general, most of which is applicable cross-language.
I am trying to figure out how to convert hex into a string and integer so I can manipulate an RGB light on my arduino micro-controller through it's serialport. I found a good example on the java website, but I'm having a difficult time understanding some of the methods and I am getting hung up. I could easily just copy-paste this code and have it work but I want to fully understand it. I will add comments to my understandings and hopefully someone can provide some feedback.
public class HexToDecimalExample3{
public static int getDecimal(String hex){ //this is the function which we will call later and they are declaring string hex here. Can we declare string hex inside the scope..?
String digits = "0123456789ABCDEF"; //declaring string "digits" with all possible inputs in linear order for later indexing
hex = hex.toUpperCase(); //converting string to uppercase, just "in case"
int val = 0; //declaring int val. I don't get this part.
for (int i = 0; i < hex.length(); i++) //hex.length is how long the string is I think, so we don't finish the loop until all letters in string is done. pls validate this
{
char c = hex.charAt(i); //char is completely new to me. Are we taking the characters from the string 'hex' and making an indexed array of a sort? It seems similar to indexOf but non-linear? help me understand this..
int d = digits.indexOf(c); //indexing linearly where 0=1 and A=11 and storing to an integer variable
val = 16*val + d; //How do we multiply 16(bits) by val=0 to get a converted value? I do not get this..
}
return val;
}
public static void main(String args[]){
System.out.println("Decimal of a is: "+getDecimal("a")); //printing the conversions out.
System.out.println("Decimal of f is: "+getDecimal("f"));
System.out.println("Decimal of 121 is: "+getDecimal("121"));
}}
To summerize the comments, it's primarily the char c = hex.charAt(i); AND the val = 16*val + d; parts I don't understand.
Ok, let's go line for line
public static int getDecimal(String hex)
hex is the parameter, it needs to be declared there, so you can pass a String when you call the function.
String digits = "0123456789ABCDEF";
Yes, this declares a string with all characters which can occur in a hexadecimal number.
hex = hex.toUpperCase();
It converts the letters in the hex-String to upper case, so that it is consistent, i.e. you always have F and never f, no matter which is being input.
int val = 0;
This is the variable where the corresponding decimal value will later be in. We will do our calculations with this variable.
for (int i = 0; i < hex.length(); i++)
hex.length() is the number of characters in the hex-String provided. We execute the code inside this for loop once per character.
char c = hex.charAt(i);
Yes, char represents a single character. We retrieve the character from the hex-String at index i, so in the first iteration it is the first character, in the second iteration the second character and so on.
int d = digits.indexOf(c);
We look which index the character has in the digit-String. In that way we determine the decimal representation of this specific digit. Like 0-9 stay 0-9 and F becomes a 15.
val = 16*val + d;
Let's think about what we have to do. We have the decimal value of the digit. But in hexadecimal we have this digit at a specific position with which it gets multiplied. Like the '1' in '100' is actually not a 1, but 100 * 1 because it is at this position.
10 in hexadecimal is 16 in decimal, because we have 1 * 16. Now the approach here is a little bit complicated. val is not uninitialized. val is 0 at the beginning and then contains the cumulated values from the previous iterations. Since the first character in the String is the highest position we don't know directly with what we have to multiply, because we don't know how many digits the number has (actually we do, but this approach doesn't use this). So we just add the digit value to it. In the consecutive iterations it will get multiplied by 16 to scale it up to the corresponding digit base value. Let me show you an example:
Take 25F as hex number. Now the first iteration takes the 2 and converts it to a 2 and adds it to val. The 16 * val resolves to 0 so is not effective in the first time.
The next iteration multiplies the 2 with 16 and takes the 5 (converted to 5) and adds it to val. So now we have (I split it mathematically so you understand it):
2 * 16 + 5
Next we get the F which is decimal 15. We multiply val by 16 and add the 15.
We get 2 * 256 + 5 * 16 + 16 (* 1), which is actually how you calculate the decimal value of this hex value mathematically.
Another possibility to compute val is:
val += Math.pow(16, hex.length() - i - 1) * d;
I am developing a small application where I am given some string "MRUGDQ" and a shift value 3 for example. Then I shift each letter to left by 3 and the result would be "JORDAN". For instance M would be replaced by J and R would be replaced by O and so on.
So now this is the approach I was thinking of using, but I was wondering if this is efficient and can I improve my solution?
Assumptions I make:
I am assuming my string will be either capital A to Z letter or small a to z letter and therefore the ascii range is from 65 to 90 and 97 to 122 respectively.
Pesudo Code
get ascii value of char
(assume char happens to be between the capital letter range)
add the shift value to the char ascii value
if new ascii value <= 90
replace old letter by new letter
else
int diff = new ascii value - 90
while (new ascii value <= 90) {
decrement diff value by 1
increment new ascii value by 1
}
add remaining diff to 65 and set that as new ascii value
replace old letter by new letter
Do that for each letter in the string.
Please let me know if my approach is correct or if I can be more efficient.
I don't see much to improve, except your handling of the new char is out of range.
If you like to "roll" the overlapping amount back to the beginning of your range, than just calculate: (x % 90) + 64(*) (with x being the ascii value after adding the shift value).
Example:
'Y' (89) + 3 = '\' 92
92 % 90 = 2
2 + 64 = 'B' (66)
You need to start from 64, to avoid skipping over 'A', which has the value 65.
(*) The general formula is: (value % upper bound) + (lower bound - 1).
You could also use (value % upper bound + 1) + lower bound.
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 am trying to assign a number to a letter grade that a user inputs. The user will input a letter such as A, B, or C and then based on what they enter a value is stored in an integer.
I figured the easiest way to do this was setup an array such as:
char[] grade = char[] grade = {'A','B','C','D','F'};
grade[0] = 4;
grade[1] = 3;
// ... as so on
So, whenever a user inputs 'A' for their grade, I use the 4 when I need to.
I am trying to figure out how to read an input (JOptionPane) and read the letter they enter to the corresponding value I have assigned it. How do I go about parsing the letter input based on my array?
I'm not sure, whether I understood you right:
int grade (char input)
{
return 5 - (input - 'A');
}
Think of it as a graph. In computer encoding, Ascii or UTF8, the characters A-F are sequentially encoded, with A being the lowest, but not 0 or 1, but 65 or something, which we don't remember exactly.
5 | *
4 | *
3 | *
2 | *
1 | *
0 +-- ... ------------------*----->
A B C D E F
65 6 7 8 9 70
Drawing this graph, I mentioned that you jump form D to F - is that intentionally? If not:
If we subtract from 5 the difference from input and 'A', we get 5 - 0 for 'A', and 5 - 1 for 'B' and so on. Since we don't want to look up the number for 'A', we use 'A' directly, which is fine, since we can perform arithmetics on characters.
We could as well write
return 70 - input;
or
return 'F' - input;
The standard form of a linear equation is y = mx + n, where n is the cut through the y-axis (70), and m = -1, the gradient, negative in our case.
It might be easier to just cast the character to an int. A char basically has an int value. Doing this:
int i = (char)'A';
will yield 65. For a lower case a it would be 97. You could cast the char to int, then use that value to do bounds checking and some arithmetic. Sequential letters will yield sequential integers. This is safe since you're running on a JVM and don't have to take bizarro character set orders for different platforms into account.
Apart from that, seeing how you have limited allowed inputs, a map could work well too:
Map<Character, Integer> grades = new HashMap<Character, Integer>();
grades.put('A', 4); //optionally also: grades.put('a' 4);
...
Type params and auto-boxing and unboxing makes this a lot more convenient these days.