how to convert a string value to integer without using Integer.parseInt()? - java

I have this input like
String s = "6" , ss="99 , sss = "99999";
i need to store these values in an int reference variable ,
without using Integer.parseInt
any suggestion ? , no full code , just the hints ??

What about Scanner?
int a=new Scanner(s).nextInt();
Without util.
public static int parseInt(String s)
{
int ans=0;
for(int i=s.length()-1;i>=0;i--)
{
ans+=(s.charAt(i)-'0');
ans*=10;
}
return ans/10;
}

public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0';
for(char c:ch){
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
System.out.println("\"76289\" == "+convert_String_To_Number("76289"));
System.out.println("\"90087\" == "+convert_String_To_Number("90087"));
}
}
See more at this URL.

Try to get each char from the string and then the value of each char. 0 has a value of 48 so
char c = '9';
int i = c - 48;
Now i = 9. After that you only need to multiply this value with the appropriate power of 10 and add it to the total

public class ConvertIntoInt {
public static void main(String []args) {
String numStr = "3256";
char ch[] = numStr.toCharArray();
int sum = 0;
// Get ASCII value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
System.out.println("Temp Ascii:" + tmpAscii);
sum = (sum * 10) + (tmpAscii - zeroAscii);
System.out.println(sum);
}
System.out.println(sum);
}
}

Related

Getting Numberformat exception with unknown source. How to fix this

How to fix this issue?
java.lang.NumberFormatException: at java.lang.NumberFormatException.forInputString(Unknown Source)
I am doing some example problem and my code is working fine for the first string and digit. (Commented one)
But when change the new string and digit (Current one) I am getting this error :
java.lang.NumberFormatException: For input string: "299858953917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at com.codejam.q1.problems.maxResult.removeDigit(maxResult.java:21)
at com.codejam.q1.problems.maxResult.main(maxResult.java:10)
Here is my code. Anywhere I am missing something ?
public class maxResult {
public static void main(String[] args) {
//String str = "1231";
String str = "2998589353917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471";
//char digit = '1';
char digit = '3';
System.out.println(removeDigit(str,digit));
}
public static String removeDigit(String number, char digit) {
long result = 0;
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
long myNum = Long.parseLong(myStr);
if(myNum > result) {
result = myNum;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
String s = String.valueOf(result);
return s;
}
}
Even though I change int to long but no change in result.
Your number is too big for a long value. The maximum long value is 9,223,372,036,854,775,807. You can use BigInteger, which essentially has no limit.
Using long
long result = 0;
// ...
long myNum = Long.parseLong(myStr);
if(myNum > result) {
result = myNum;
}
// ...
String s = String.valueOf(result);
return s;
Using BigInteger
import java.math.BigInteger;
// ...
BigInteger result = BigInteger.ZERO;
// ...
BigInteger myNum = new BigInteger(myStr);
result = myNum.max(result);
// ...
return result.toString();
The number is too long for a long. Longs go from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,808.
Try doing this :
public static String removeDigit(String number, char digit) {
double temp = 0;
String result="";
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
double myNum = Double.parseDouble(myStr);
if(myNum > temp) {
temp = myNum;
result=myStr;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
return result;
}
The problem you get is that you are exceeding the limit of the int and the long. Let us see the limits of some number storing types and then use the best one:
Type
Size
Value
Exceeds
int
32 bit
-2,147,483,648 to 2,147,483,647
Yes
long
64 bit
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Yes
float
32 bit
3.40282347 x 1038 to 1.40239846 x 10-45
Yes
double
64 bit
1.7976931348623157 x 10308 to 4.9406564584124654 x 10-324
Yes
BigInteger
32 bit
2^64billion
No
Here, we find that BigInteger is the class we need to use. So, instead of using a long or int for it, use BigInteger. To know more about BigInteger, visit here.
Also to know how to use a big integers refer to the answer here
You can use BigDecimal instead of long.
public class Application {
public static void main(String[] args) {
//String str = "1231";
String str = "2998589353917872714814599237991174513476623756395992135212546127959342974628712329595771672911914471";
//char digit = '1';
char digit = '3';
System.out.println(removeDigit(str,digit));
}
public static BigDecimal removeDigit(String number, char digit) {
BigDecimal result = BigDecimal.ZERO;
for(int i = 0; i<number.length(); i++) {
char num = number.charAt(i);
if(num == digit) {
String myStr = number.substring(0, i) + number.substring(i + 1);
try{
BigDecimal myNum = new BigDecimal(myStr);
if(myNum.compareTo(result)>0) {
result = myNum;
}
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
return result;
}
}

How do you print the highest and smallest number of ASCII value in string java

I found it, thank u mate. I actually too confuse yesterday, till i forget everything that i learnt. So here is my code, what do you think?
I just don't know why my minChar not working when i delete this code :
if(stringValue.charAt(i) != 32){
public class MyString {
public static void main(String[] args) {
String stringValue = "Hello World";
SearchMyString str = new SearchMyString(stringValue);
str.stringInfo();
}
}
class SearchMyString{
private char maxChar;
private char minChar;
String stringValue;
int ascii;
public SearchMyString(String stringValue){
this.stringValue = stringValue;
}
char getMinChar(String stringValue, int n){
minChar = 'z';
for(int i = 0;i<n-1;i++){
if(stringValue.charAt(i)<minChar){
if(stringValue.charAt(i) != 32){
minChar = stringValue.charAt(i);
ascii = (int)stringValue.charAt(i);
}
}
}
return minChar;
}
public void stringInfo(){
int size = stringValue.length();
System.out.println("Smallest char : "+getMinChar(stringValue,size) + "\tASCII : " + ascii);
}
}
Use this method:
public static char getMaxChar(String a){
char max = a.charAt(0);
for (int i=0; i<a.length(); i++){
if ((a.charAt(i) > max)){
max = a.charAt(i);
}
}
return max;
}
Test case:
ACBDEFG
Returns
G
So what did we change?
For starters, if we are trying to get the character in the String that has the highest char int value, we don't need n. We are looping through the String, so all we need is the length, which can already be supplied by the .length() method.
To call the method, just do:
SearchMyString search = new SearchMyString();
search.getMaxChar(nama);
EDIT: So to make the method more reliable, instead of automatically setting max to 'A', we can set it to the first char of a (e.g, a.charAt(0))

Convert a number of the datatyp String to char

I try to convert numbers of a String in to an array with the datatyp char. My problem is, that the number in my array is everytime 48 to high. I also know that the problem has something to do with ASCII table. What can i do to solve this problem?
package Test;
public class Main {
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber);;
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
}
use
number[indexNumber] = calculation.charAt(iNumber) - '0';
Digit 0 has an ASCII value of 48. The range of ASCII value for 0-9 digits is from 48-57. So, whenever you extract a character, let's say '5', you store 53 instead of 5 in the array. So try to use the below code modification where you subtract character '0':
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber)-'0'; //modified
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}

Java:How do I make the "char" parameter into a String parameter in this specific java method?

public static int getNthOccurrence(int n, char find, String str)
{
int counter=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==find)
{
counter++;
if(counter==n)
return i;
}
}
return -1;
}
I have already seen this thread Java: method to get position of a match in a String?
The code runs that:
int n=getNthOccurrence(3,'n',"you arent gonna find me");
output: 13
You can make a char into a String by simply doing this
String theString = yourChar + "";
Your code could look something like this !spoiler below!
public static int getNthOccurrence(int n, char find, String str)
{
String f = find + "";
int counter = 0;
for (String c : str.split("")){
if (c.equals(f)) n--;
if (n < 1 ) return counter;
counter++;
}
return -1;
}
}
Once you've changed the parameter type to String:
public static int getNthOccurrence(int n, String find, String str)
Use String.indexOf(String, int):
i = -find.length();
for (int count = 0; count < n; ++count) {
i = str.indexOf(find, i + find.length());
if (i < 0) break;
}
return (i >= 0) ? i : -1;
(Note that String.indexOf(char, int) is a preferable way to do it with char, as in the case of the original code).

Converting Decimal into binary in java

I am trying to convert decimal to binary numbers from the user's input using Java but so far, I'm running into errors I'm not sure why. What am I doing wrong? Don't mind the naming, ultimately I would like to convert decimal into binary without using if and while statements. Also without using the decimaltobinary string.
Thanks a lot.
package r
public static void main(String[] args) {
int number;
int remainder;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
remainder= number %2;
System.out.print(remainder);
{
return null;
This is what I have so far.
This is how to convert a decimal to binary :
Using for loop :
public class DecimalToBinary {
public void printBinaryFormat(int decimalNumber){
int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
remainder = decimalNumber % 2;
decimalNumber /= 2;
System.out.print(remainder);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Using while loop :
public class DecimalToBinary
{
public void printBinaryFormat(int number){
int binary[] = new int[25];
int index = 0;
while(number > 0){
binary[index++] = number%2;
number = number/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Hope I helped .
Happy Coding :D
Try this:
String binaryString = Long.toBinaryString(Double.doubleToRawLongBits(yourDecimalNumber));
Where yourDecimalNumber is the name of the decimal variable that you want to convert to binary.
You can also use a for loop and bitwise operation without using any if or while statements like so:
int number = 10;
String binaryString = "";
final int intBitSize = 32; // 32 is the number of bits in an int.
for(int i=0; i<intBitSize; i++)
{
binaryString = String.valueOf(number&1) + binaryString;
number = number >>> 1;
}
System.out.println(binaryString);

Categories

Resources