I know this is trivial, but I can't find the proper explication. I have the following code
str="1230"
int rez=str.charAt(3) - '0';
rez=3;
How does this parsing work?
As long as the character is a digit, you can get the equivalent int value by subtracting '0'. The ASCII coding for '0' is decimal 48, '1' is decimal 49, etc.
So '8' - '0' = 56 - 48 = 8;
For your number, you can parse the entire string like this (assuming all the characters are digits, otherwise the result wouldn't make sense).
String v = "1230";
int result = 0; // starting point
for (int i = 0; i < v.length(); i++) {
result = result* 10 + v.charAt(i) -'0';
}
System.out.println(result);
Prints
1230
Explanation
In the above loop, first time thru
result = 0 * 10 + '1'-'0 = 1
second time thru
result = 1 * 10 + '2'-'0' = 12
third time thru
result = 12 * 10 + '3'-'0' = 123
last time thru
result = 123 * 10 + '0'-'0' = 1230
"Behind the scene" a char is just an int with a specific range (very simplified explanation).
Try following code to convince yourself:
System.out.println((int) '0'); // this won't output 0
System.out.println((int) 'a'); // this work as well
This is why arithmetic operations are possible on chars.
Related
I was trying to find the sum of digits of a BigInteger and found this code.
BigInteger big = BigInteger.valueOf(2).pow(1000);
String digits = big.toString();
int sum = 0;
for(int i = 0; i < digits.length(); i++) {
int digit = (int) (digits.charAt(i) - '0');
sum = sum + digit;
}
System.out.println(sum);
I don't understand why - '0' is added in 6th line of the code.
int digit = (int) (digits.charAt(i) - '0');
If I remove that part it gives me a wrong answer.
For example sum of digits of 16 without - '0' gives 103 as the answer instead of 7.
So, can anyone explain the importance of that part in the code?
Any help is appreciated.
The code digits.charAt(i) gives you the ASCII code for the digit. So if you look at an ASCII table, you'll see the value of the character 7 is 55 and the value of character 0 is 48. If you subtract 0 from 7, you'll get 7, which is the digit you're looking for.
For example if you take a '5' from digits.getCharAt(i):
'5' - '0' = ?
According to the ASCII table Can be translated to:
53 - 48
Which is 5 and it's the result you're looking for
Given a string as input, convert it into the number it represents. You can assume that the string consists of only numeric digits. It will not consist of negative numbers. Do not use Integer.parseInt to solve this problem.
MyApproach
I converted string to char array and stored the original number but I am unable to convert it into a single number
I tried converting individual elements but the digits can be of any length.So,It was difficult to follow that approach.
Hint:I have a hint that the numbers can be added using place values
For e.g if the number is 2300.I stored each number in the form of arrays.Then it should be 2*1000+3*100+0*10+0=2300
But I am unable to convert it into code.
Can anyone guide me how to do that?
Note I cannot use any inbuilt functions.
public int toNumber(String str)
{
char ch1[]=str.toCharArray();
int c[]=new int[ch1.length];
int k=0;
for(int i=0;i<c.length;i++)
{
if(ch1[i]==48)
{
c[k++]=0;
}
else if(ch1[i]==49)
{
c[k++]=1;
}
else if(ch1[i]==50)
{
c[k++]=2;
}
else if(ch1[i]==51)
{
c[k++]=3;
}
else if(ch1[i]==52)
{
c[k++]=4;
}
else if(ch1[i]==53)
{
c[k++]=5;
}
else if(ch1[i]==54)
{
c[k++]=6;
}
else if(ch1[i]==55)
{
c[k++]=7;
}
else if(ch1[i]==56)
{
c[k++]=8;
}
else if(ch1[i]==57)
{
c[k++]=9;
}
}
}
You don't need to do powers or keep track of your multiplier. Just multiply your running total by 10 each time you add in a new digit. And use c - '0' to turn a character into a number:
int n = 0;
for (int i = 0; i < str.length(); i++) {
n = n * 10 + str.charAt(i) - '0';
}
So for example for 1234 it goes
0 * 10 + 1 = 1
1 * 10 + 2 = 12
12 * 10 + 3 = 123
123 * 10 + 4 = 1234
A digit character ('0'-'9') can be converted into an integer value (0-9) using:
ch - '0'
This is because the digit characters are all consecutive in ASCII/Unicode.
As for calculating the full number, for the input 2300, you don't want:
2 * 1000 + 3 * 100 + 0 * 10 + 0
Instead, you'll want a more incremental approach using a loop:
r = 0
r = r * 10 + 2 (2)
r = r * 10 + 3 (23)
r = r * 10 + 0 (230)
r = r * 10 + 0 (2300)
This is much better than trying to calculate 1000 (Math.pow(10,3)), which your formula would require.
This should be enough information for you to code it. If not, create a new question.
If you loop through the char array you have and take the last value, put it through an if statement and add to an to number integer whatever that number is (use 10 if statements). Next go to the second to last value, and do the same thing only this time multiply the resulting numbers by 10 before adding it to the total number. Repeat this using 1 * 10^(value away from end) being multiplied to the number gotten from the if statements.
Well what comes to my mind when seeing this problem is to multiply the numbers you are getting with your current code with the place they have in the charArray:
int desiredNumber = 0;
for(int k=1; k<=c.length; k++) {
desiredNumber += c[k] * (Math.pow(10, c.length - k));
}
If you are not allowed to use the Math.pow() function then simply write one yourself with aid of a loop.
Greetings Raven
You can do
int no = 0;
for(int i = 0; i < c.length; i++){
no += c[i] * Math.pow(10, c.length - 1 - i);
}
I'm trying to make a UUencode algorithm and part of my code contains this:
for(int x = 0; x < my_chars.length; x++)
{
if((x+1) % 3 == 0)
{
char first = my_chars[x-2];
char second = my_chars[x-1];
char third = my_chars[x];
int first_binary = Integer.parseInt(Integer.toBinaryString(first));
int second_binary = Integer.parseInt(Integer.toBinaryString(second));
int third_binary = Integer.parseInt(Integer.toBinaryString(third));
int n = (((first << 8) | second) << 8) | third;
System.out.print(my_chars[x-2] + "" + my_chars[x-1] + my_chars[x] + Integer.toBinaryString(n));
}
}
System.out.println();
System.out.println(Integer.toBinaryString('s'));
What I'm trying to achieve is to combine those 8 bits from the chars that I get into a big 24 bits int. The problem I'm facing is that the result is a 23 bit int. Say my first 3 chars were:
'T' with a binary representation of 01010100
'u' with a binary representation of 01110101
'r' with a binary representation of 01110010
The result that I get from my program is a int formed from these bits:
10101000111010101110010
Which is missing the 0 at the beginning from the representation of 'T'.
Also I have included the last 2 lines of code because the binary string that I get from 's' is: 1110011 which is missing the 0 at the beginning.
I have checked if I scrolled by mistake to the right but it does not seem that I have done so.
The method Integer.toBinaryString() does not zero-pad the results on the left; you'll have to zero-pad it yourself.
This value is converted to a string of ASCII digits in binary (base 2)
with no extra leading 0s.
Basically, I'm trying to write a program that converts a number from base 2 to base 10. What I tried doing was translating the process listed on this website under the "Doubling method" into a for loop, but for some reason the numbers I'm getting are way to big.
The basic formula is (2 * previousTotal) + (currentDigit of the ArrayList that holds the user's inputted binary number) = previousTotal.
So for 1011001 in binary, the math would be:
(0 x 2) + 1 = 1
(1 x 2) + 0 = 2
(2 x 2) + 1 = 5
(5 x 2) + 1 = 11
(11x 2) + 0 = 22
(22 x 2) + 0 = 44
(44 x 2) + 1 = 89
The console however, prints out 6185 as the result. I'm thinking it might have something to do with me using an ArrayList of characters, but the charWhole.size() returns 7, which is how many digits are in the user's binary number. As soon as I do charsWhole.get(w); however, I start getting big numbers such as 49. I'd really appreciate some help!
I wrote out this loop, and according to some print statements that I placed throughout the code and my variable addThis seems to be where the problem is. The console prints out a final total of 6185, when 1011001 in base 10 is actually 89.
public static void backto2(){
System.out.println("What base are you coming from?");
Scanner backToB10 = new Scanner(System.in);
int bringMeBack = backToB10.nextInt();
//whole
System.out.println("Please enter the whole number part of your number.");
Scanner eachDigit = new Scanner(System.in);
String theirNumber = eachDigit.nextLine();
String str = theirNumber;
ArrayList<Character> charsWhole = new ArrayList<Character>();
for (char testt : str.toCharArray()) {
charsWhole.add(testt);
}
System.out.println(theirNumber); // User's number
System.out.println(charsWhole); // User's number separated into elements of an ArrayList
System.out.println(charsWhole.size()); // Gets size of arrayList, comes out as 7 which seems fine.
int previousTotal = 0, addThis = 0, q =0;
for( int w = 0; w < charsWhole.size(); w ++) {
addThis = charsWhole.get(w); //current digit of arraylist PROBLEM
q = previousTotal *2;
previousTotal = q + addThis; // previous total gets updated
System.out.println(q);
System.out.println(addThis);
System.out.println(q + " and " + addThis + "equals " + previousTotal);
}
System.out.println(previousTotal);
You are attempting to add a character to an integer. The implicit conversion uses the ASCII value of the character, so that '1' gets converted to 49, not 1, because 49 is the code for the character '1'. Subtract '0' to get the actual integer value.
addThis = charsWhole.get(w) - '0';
This works because the digits 0-9 are represented in ASCII as the codes 48-57, so in effect you will, for '1', subtract 49 - 48 to get 1.
You'll still have to handle cases when the character is outside the range of allowable characters.
EDIT
Java uses Unicode, but for the purposes of the codes for the digits 0-9, the codes are the same (48 thru 57, or 0x30 thru 0x39) in both ASCII and Unicode.
The problem is that you're using the chars rather than the number value they represent. In the line
addThis = charsWhole.get(w);
the value of addThis is the ascii value of the character. For '0', this is 48. Use this instead:
addThis = Integer.parseInt(charsWhole.get(w));
Another suggestion to solve the same problem:
addThis = charsWhole.getNumericValue(w);
See here for more information.
I'm working on this program that takes a binary string and converts it to decimal, using this guide to convert from binary to decimal. When I run through the for loop in my head, I get what the correct outputs would be. And yet, when I run my program, I get this strange output:
1
3
7
15
31
63
127
The actual output should look like this:
1
2
5
11
22
44
89
I cannot figure this out for the life of me. Why is my program doing this? Here's the current source code:
public class BinaryToDecimal
{
public static void main(String[] args)
{
String binary = "1011001";
int toMultiplyBy;
int decimalValue = 0;
for (int i = 1; i <= binary.length(); i++)
{
int whatNumber = binary.indexOf(i);
if (whatNumber == 0)
{
toMultiplyBy = 0;
}
else
{
toMultiplyBy = 1;
}
decimalValue = ((decimalValue * 2) + toMultiplyBy);
System.out.println(decimalValue);
}
}
}
Strings are 0 based so you should loop through the String from 0 to < the String's length, but indexOf(...), is not what you want to use since this will search for the location in the String of small ints which makes no sense. You don't care where the char equivalent of 2 is located in the String or even if it is in the String at all.
Instead you want to use charAt(...) or subString(...) and then parse to int. I would use
for (int i = 0; i < binary.length(); i++) {
int whatNumber = charAt(i) - '0'; // converts a numeric char into it's int
//...
To see what this is doing, create and run:
public class CheckChars {
public static void main(String[] args) {
String foo = "0123456789";
for (int i = 0; i < foo.length(); i++) {
char myChar = foo.charAt(i);
int actualIntHeld = (int) myChar;
int numberIWant = actualIntHeld - '0';
System.out.printf("'%s' - '0' is the same as %d - %d = %d%n",
myChar, actualIntHeld, (int)'0', numberIWant);
}
}
}
Which returns:
'0' - '0' is the same as 48 - 48 = 0
'1' - '0' is the same as 49 - 48 = 1
'2' - '0' is the same as 50 - 48 = 2
'3' - '0' is the same as 51 - 48 = 3
'4' - '0' is the same as 52 - 48 = 4
'5' - '0' is the same as 53 - 48 = 5
'6' - '0' is the same as 54 - 48 = 6
'7' - '0' is the same as 55 - 48 = 7
'8' - '0' is the same as 56 - 48 = 8
'9' - '0' is the same as 57 - 48 = 9
The numbers that represent the chars is based on the old ASCII table that gave each symbol a numeric representation. For more on this, please look here: ASCII Table
Two points:
Array indexing starts at zero, not 1, so your loop should be `for (int i=0; i
You are confusing indexOf() with substring(). In your case, binary.indexOf(i) does the following. First, the integer i is converted to a string. Then binary is searched left-to-right for a substring matching the string value of i. The first time through the loop i==1. This returns zero, because there's a 1 at index zero in binary. The second time, the value of i is 2. There's no 2 in binary, so this returns zero. For i==3, you're looking for a string 3 in binary, which will never be true.
Take a look at the String#substring() method, which is what I believe you intended.