calculating consecutive 1's in a Binary number - java

import java.util.Scanner;
import java.util.Arrays;
class Solve
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int i=0,count=0;
int[] arr = new int[10];
int n =in.nextInt();
while(n!=0)
{
arr[i]=n%2;
i++;
n=n/2;
}
System.out.println(Arrays.toString(arr));
}
}
}
I just want to calculate number of consecutive 1's. ? like 1110011001 will give me answer 5.. How can i do that??

System.out.println(Integer.toBinaryString(n).replaceAll("(0|(?<!1)1(?!1))", "").length());
The regex means: replace all 0's and any 1 not preceded or followed by another 1

You can handle this as a String [Edited to sum all consecutive 1's]:
String binary = in.nextLine();
String[] arrayBin = binary.split("0+"); // an array of strings without 0's
int result=0;
for (int i=0; i < arrayBin.length; i++){
if (arrayBin[i].length()<2){
result+=0;
}
else {
result+=arrayBin[i].length();
}
}
System.out.println("Total consecutive = "+result);

We can identify two consecutive binary ones in the least significant positions like this:
(value & 0b11) == 0b11
We can move the bits in value to the right like so:
value >>>= 1;
It's important to use tripple >>> over double >> because we don't care about the sign bit.
Then all we have to do is keep track of the number of consecutive 1s:
int count(int value) {
int count = 1;
int total = 0;
while (value != 0) {
if ((value & 0b11) == 0b11) {
count++;
} else {
if (count > 1) {
total += count;
}
count = 1;
}
value >>>= 1;
}
return total;
}
Test cases:
assertEquals(0, count(0b0));
assertEquals(0, count(0b1));
assertEquals(0, count(0b10));
assertEquals(2, count(0b11));
assertEquals(5, count(0b1110011));
assertEquals(5, count(0b1100111));
assertEquals(6, count(0b1110111));
assertEquals(7, count(0b1111111));
assertEquals(32, count(-1));
If you only want the length of the maximum, I have a similar answer: https://stackoverflow.com/a/42609478/360211

You can make use of Brian Kernighan’s Algorithm for counting the highest consecutive number of 1's.
A java pseudocode would be something like this
// Initialize result
int count = 0;
// Count the number of iterations to
// reach n = 0.
while (n!=0)
{
// This operation reduces length
// of every sequence of 1s by one.
n = (n & (n << 1));
count++;
}

public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int counter = 0, max = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 1){
counter += nums[i];
} else{
counter = nums[i];
}
max = Math.max(counter, max);
}
return max;
}
}

To this problem one trick which we can use here with help of some Java operators.
& operator and left shift (<<) in java.
Code snippet will be like :
public getConsecutiveCount(int inputNumber)
{
int count = 0 ;
while(inputNumber != 0)
{
inputNumber = inputNumber & (inputNumber << 1);
count++;
}
}
Explanation :
This function is taking input (ex : we want to check how many
consecutive 1's integer 6 have in its binary representation)
so out input number will be like :
inputNumber = ((110) & ((110)<<1)) {This left shift will result in 100 so final op :
110 & 100 which 100 , every time '0' is added to
our result and we iterate until whole number will
be zero and value of our count variable will be
our expected outcome }

To find Maximum consecutive 1's in binary(like 101)
int n = Convert.ToInt32(Console.ReadLine());
string[] base2=Convert.ToString(n,2).Split('0');
int count=0;
foreach(string s in base2)
count=s.Length>count?s.Length:count;
Console.WriteLine(count);

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String bs = Integer.toBinaryString(n);// bs=Binary String
char[] characters = bs.toCharArray();
int max = 1;
int temp = 1;
for (int i = 0; i < characters.length - 1; i++) {
if (characters[i] == characters[i + 1] & characters[i] == '1' & characters[i + 1] == '1') {
temp++;
if (temp > max) {
max = temp;
}
} else {
temp = 1;
}
}
System.out.println(max);
}

/* Given a decimal number print maximum number of consecutive 1's after binary conversion */
import java.io.*;
import java.util.*;
public class Solution {
public void countBinaryOne(int num){
int var =0, countOne= 0, maxCt=0;
while(num>0){
var= num%2;
if(var==1){
countOne=countOne+1;
}else{
if(maxCt<countOne){
maxCt= countOne;
countOne=0;
}else{
countOne=0;
}
}
num=num/2;
}
System.out.println(Math.max(countOne,maxCt));
}
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int n= in.nextInt();
Solution sol= new Solution();
sol.countBinaryOne(n);
}
}

public static void digitBinaryCountIfOne(int n){
int reminder=0, sum=0, total = 0;
while(n>0)
{
reminder = n%2;
n/=2;
if(reminder==1){
sum++;
if(sum>=total)
total=sum;
}else{
sum=0;
}
}
System.out.println(total);
}

Related

To count unique digits in a given number N in java

Given a number N, for example, take 1091, here the count of digits is 4 but the count of unique digits is 3 i.e. 1, 0 & 9 are unique (since 1 is repeated).
I have tried breaking the number into individual digits and adding it to ArrayList and later converting it to an array. Then, iterating through the array and increasing the count of unique digits by 1 every time I got a unique digit in the array, But I have not got the required output. Kindly someone help in finding the unique digits count in a given number in Java.
import java.util.ArrayList;
public class UniqueDigits {
static int uniqueDigitCount(int n) {
ArrayList<Integer> ar = new ArrayList<>();
int temp = n;
int count = 1;
do {
ar.add(temp % 10);
temp /= 10;
}
while (temp > 0);
Integer[] arr = new Integer[ar.size()];
arr = ar.toArray(arr);
if (arr.length > 0) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] != arr[i + 1]) {
count++;
}
}
return count;
} else {
return 0;
}
}
public static void main(String[] args) {
System.out.println(uniqueDigitCount(1091));
}
}
static int uniqueDigitCount(int n) {
HashSet<Integer> hs = new HashSet<Integer>();
int count;
if(n == 0)
{
count = 1;
}
else
{
while(n > 0)
{
hs.add(n % 10);
n /= 10;
}
count = hs.size();
}
return count;
}
A HashSet stores only unique elements. So, when we return the length of the HashSet after adding each digit of the input integer to it, we can obtain the count of unique digits in that input.
This could be done with a set. A set is a collection of unique elements. Putting all characters (digits) into a set will result in the duplicates being discarded. Its size() will then return the distinct elements.
Using streams:
int number = 1091;
long uniques = String.valueOf(number).chars()
.mapToObj(c -> c)
.collect(Collectors.toSet())
.size();
Or leveraging a count on the stream:
String.valueOf(number).chars()
.distinct()
.count();
import java.util.ArrayList;
import java.util.HashSet;
public class UniqueDigits {
static int uniqueDigitCount(int n) {
ArrayList<Integer> ar = new ArrayList<>();
int temp = n;
int count = 1;
do {
ar.add(temp % 10);
temp /= 10;
} while (temp > 0);
Integer[] arr = new Integer[ar.size()];
arr = ar.toArray(arr);
HashSet<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < arr.length - 1; i++) {
hs.add(arr[i]);
}
return hs.size();
}
public static void main(String[] args) {
System.out.println(uniqueDigitCount(1091));
}
}
For a detailed explanation do check my article on gfg (Count of unique digits in a given number N):
import java.util.*;
class UniqueDigits {
// Function that returns the count
// of unique digits of number N
public static void
countUniqueDigits(int N)
{
// Initialize a variable to
// store count of unique digits
int res = 0;
// Initialize cnt array to
// store digit count
int cnt[] = { 0, 0, 0, 0, 0,
0, 0, 0, 0, 0 };
// Iterate through digits of N
while (N > 0) {
// Retrieve the last
// digit of N
int rem = N % 10;
// Increase the count
// of the last digit
cnt[rem]++;
// Remove the last
// digit of N
N = N / 10;
}
// Iterate through the
// cnt array
for (int i = 0;
i < cnt.length; i++) {
// If frequency of
// digit is 1
if (cnt[i] == 1) {
// Increment the count
// of unique digits
res++;
}
}
// Return the count of unique digit
System.out.println(res);
}
public static void main(String[] args)
{
// Given Number N
int N = 2234262;
// Function Call
countUniqueDigits(N);
}
}

prime factorization decryption

I have a program that is supposed to decrypt a number to its primes. The primes also have an order: for instance, 2 is the 1st prime number, 3 is the second 5 is the third and so on. The indexes are 1 is for a, two is for b, three is for c and so on. I don't know how to compare the two array lists in order to assign an index to each prime so I can decode a word which is encrypted in the number 72216017. The number 72216017 has the primes 17,19,47,67,71. If 2,3,5,7,11... are a,b,c,d,e... these five prime numbers make up the word ghost, I just don't know how to assign and sort these numbers by their index.
package name;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PrimeFactorsEffective {
private static int z;
private int w = z;
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
if (n > 1) {
factors.add(n);
System.out.println(factors);
z = Collections.max(factors);
}
}
return factors;
}
public static void main(String[] args) {
System.out.println("Primefactors of 72216017");
for (Integer integer : primeFactors(72216017)) {
System.out.println(integer);
}
List<Integer> factors1 = new ArrayList<Integer>();
List<String> index1 = new ArrayList<String>();
int i;
int element = 0;
int num = 0;
int maxCheck = z; // maxCheck limit till which you want to find prime numbers
boolean isPrime = true;
String primeNumbersFound = "";
//Start loop 1 to maxCheck
for (i = 1; i <= maxCheck; i++) {
isPrime = CheckPrime(i);
if (isPrime) {
primeNumbersFound = primeNumbersFound + i + " ";
factors1.add(i);
factors1.get(num);
}
}
System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
System.out.println(factors1);
}
public static boolean CheckPrime(int numberToCheck) {
int remainder;
for (int i = 2; i <= numberToCheck / 2; i++) {
remainder = numberToCheck % i;
if (remainder == 0) {
return false;
}
}
return true;
}
}
You can store the primes in a List (primes in this list will be in increasing order). Now you can use Collections.BinarySearch to get the index of the prime for which you wan to find the corresponding alphabet. Once you got the index (index here according to you starts from 1, so a's index is 1, b's index is 2, c's index is 3 and so on) you can do simply something like char currentCharacter = (char) ('a' + primeIndex - 1) and the variable currentCharacter will store the alphabet corresponding to primeIndex.
Some other minor things that I'd like to suggest:
Which checking whether a number is prime or not, you can simply check upto square-root of numberToCheck. So you can replace your loop for (int i = 2; i <= numberToCheck / 2; i++) to for (int i = 2; i*i <= numberToCheck; i++). Note that It is not a good idea to calculate square-root using Math.sqrt, instead you can have a condition like i*i <= numberToCheck.
Please refrain from naming your packages that seem to be random.
As of Java SE 7 explicit type-arguments while initializing the list are not required. You can replace List<Integer> factors1 = new ArrayList<Integer>() with List<Integer> factors1 = new ArrayList<>(). Please read this for more information.
Your factor method don't really look good to me, it don't give correct results. Please see the following method that gives correct result:
{{
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<>();
for (int i = 2; n>1; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
z = Collections.max(factors);
return factors;
}

Checking if an integer is a circular prime number without using String

I have to write a boolean method that checks if a number n is a circular prime, using only integer computations, so no Strings. I wrote two other methods that have to be included.
boolean isPrime(int n) {
if (n < 1) {
return false;
} else if (n == 1 || n == 2) {
return true;
} else if (n % 2 != 0) {
for (int i = 3; i < n; i+=2) {
if (n % i == 0) {
return false;
}
}
return true;
} else {
return false;
}
}
This checks if the number is a prime.
int largestPowerOfTen(int n) {
for (int i = 1; i < n * 10; i*=10) {
if (n / i == 0) {
return i / 10;
}
}
return 1;
}
This returns the largest power of ten of the number. For instance, 23 would return 10, 704 would return 100, etc.
I had the idea to put every digit into an array and move the digits around from there, but I'm stuck at the moving part.
boolean isCircularPrime(int n) {
ArrayList<Integer> k = new ArrayList<Integer>();
int i = 0;
while (n != 0) {
k.add(n % 10);
n /= 10;
i++;
}
//???
}
So how do I move the digits around?
Assuming a "circular prime number" is a number that is a prime number for all rotations of the digits...
You can't just rotate the number, because zeroes won't be conserved.
First break up the number into an array - each digit of the number an element of the array. Use n % 10 to find the last digit, then n /= 10 until n == 0.
Create a method the generates a number from the array with a specified starting index. This is the crux of the problem, and here's some code:
private static int generate(int[] digits, int index) {
int result = 0;
for (int i = 0; i < digits.length; i++) {
result = result * 10 + digits[(index + i) % digits.length];
}
return result;
}
Then loop over every possible starting index for your digits and check if it's prime.
The remaining code I leave to the reader...
import java.util.Scanner;
class CircularPrime
{
public boolean prime(int n)
{
int lim=n,count=0;
for(int i=1;i<=lim;i++)
{
if(n%i==0)count++;
}
if(count==2)
return true;
else
return false;
}
public int circlize(int n)
{
int len,x,y,circle;
len=(""+n).length();
x=n/(int)Math.pow(10,len-1);
y=n%(int)Math.pow(10,len-1);
circle=(y*10)+x;
return circle;
/**
Another way using String
String str = Integer.toString(n);
String arr = str.substring(1)+str.charAt(0);
int a = Integer.parseInt(arr);
return a;
**/
}
public void check(int n)
{
int a=n;
boolean flag=true;
System.out.println("OUTPUT:");
do
{
if(!(prime(a)))
{
flag=false;
break;
}
a=circlize(a);
System.out.println(a);
}while(a!=n);
if(flag)System.out.println(n+" IS A CIRCULAR PRIME");
else System.out.println(n+" IS NOT A CIRCULAR PRIME");
}
public static void main(String ar[])
{
CircularPrime obj = new CircularPrime();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n=sc.nextInt();
obj.check(n);
}
}

Next Prime number Java only working with certain numbers

This function its only working for certain numbers, but for 15, or 5 it does not give me correct next prime.
public static int nextPrime(int n) {
boolean isPrime = false;
int m = (int) Math.ceil(Math.sqrt(n));
int start = 3;
if (n % 2 == 0) {
n = n + 1;
}
while (!isPrime) {
isPrime = true;
for (int i = start; i <= m; i = i + 2) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (!isPrime) {
n = n + 2;
}
}
return n;
}
You don't need to go upto sqrt(n), you need to go upto sqrt(number) that you are evaluating
for example consider you pass n = 5
it will start loop from 3 and it will end the loop at 4 that is not what you need to find next prime number
outer loop
start from n + 1 until you find prime
inner loop
you should start from 3 and sqrt(numberUnderIteration)
You're setting your boundary at the square root of the original number only. In order for you to check if every next number works, you need to recalculate the boundary whenever the n value is changed. So, put int m = (int) Math.ceil(Math.sqrt(n)); inside of your while loop.
You also need to increment n by 1 before you start any calculations, or it will accept n itself as a prime number if it is one. For example, nextPrime(5) would return 5 because it passes the conditions.
And finally, you don't need to increment n by 2 at the end of your while loop because if you are on an even number, it will break out (keep adding 2 to an even number will always be even). I've commented the part of your code that I changed:
public static int nextPrime(int n) {
boolean isPrime = false;
int start = 2; // start at 2 and omit your if statement
while (!isPrime) {
// always incrememnt n at the beginning to check a new number
n += 1;
// redefine max boundary here
int m = (int) Math.ceil(Math.sqrt(n));
isPrime = true;
// increment i by 1, not 2 (you're skipping numbers...)
for (int i = start; i <= m; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
// you don't need your "if (!isPrime)..." because you always increment
}
return n;
}
public static void main(String[] args) {
System.out.println(nextPrime(15)); // 17
System.out.println(nextPrime(5)); // 7
System.out.println(nextPrime(8)); // 11
}
You need to compute m inside the for loop.
while (!isPrime) {
isPrime = true;
int m = (int) Math.ceil(Math.sqrt(n));
// do other stuff
Your code works fine except when a prime number is given as input, your method returns input itself.
Example if 5 is your input nextPrime(5) returns 5. If you want 7 (next prime number after 5) to be returned in this case.
Just add n=n+1; at the start of your method. Hope this helps
Just for fun, I coded a quick Prime class that tracks known primes, giving a huge performance boost to finding multiple large primes.
import java.util.ArrayList;
public class Primes {
private static ArrayList<Integer> primes = new ArrayList<Integer>();
public static int nextPrime(int number){
//start it off with the basic primes
if(primes.size() == 0){
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
}
int idx = primes.size()-1;
int last = primes.get(idx);
//check if we already have the prime we are looking for
if(last > number){
//go to the correct prime and return it
boolean high = false;
boolean low = false;
int prevIdx = 0;
int spread = 0;
//keep finagling the index until we're not high or low
while((high = primes.get(idx-1) > number) || (low = primes.get(idx) <= number)){
spread = Math.abs(prevIdx-idx);
//because we always need to move by at least 1 or we will get stuck
spread = spread < 2 ? 2: spread;
prevIdx = idx;
if(high){
idx -= spread/2;
} else if(low){
idx += spread/2;
}
};
return primes.get(idx);
}
/*FIND OUR NEXT SERIES OF PRIMES*/
//just in case 'number' was prime
number++;
int newPrime = last;
//just keep adding primes until we find the right one
while((last = primes.get(primes.size()-1)) < number){
//here we find the next number
newPrime += 2;
//start with the assumption that we have a prime, then try to disprove that
boolean isPrime = true;
idx = 0;
int comparisonPrime;
int sqrt = (int) Math.sqrt(newPrime);
//make sure we haven't gone over the square root limit- also use post-increment so that we use the idx 0
while((comparisonPrime = primes.get(idx++)) <= sqrt){
if(newPrime % comparisonPrime == 0){
isPrime = false;
}
}
if(isPrime){
primes.add(newPrime);
}
}
return last;
}
}
And here is the test:
public class Test {
public static void main(String[] args){
long start;
long end;
int prime;
int number;
number = 1000000;
start = System.currentTimeMillis();
prime = Primes.nextPrime(number);
end = System.currentTimeMillis();
System.out.println("Prime after "+number+" is "+prime+". Took "+(end-start)+" milliseconds.");
number = 500;
start = System.currentTimeMillis();
prime = Primes.nextPrime(number);
end = System.currentTimeMillis();
System.out.println("Prime after "+number+" is "+prime+". Took "+(end-start)+" milliseconds.");
number = 1100000;
start = System.currentTimeMillis();
prime = Primes.nextPrime(number);
end = System.currentTimeMillis();
System.out.println("Prime after "+number+" is "+prime+". Took "+(end-start)+" milliseconds.");
}
}
This results in the following output:
Prime after 1000000 is 1000003. Took 384 milliseconds.
Prime after 500 is 503. Took 10 milliseconds.
Prime after 1100000 is 1100009. Took 65 milliseconds.
As you can see, this takes a long time the first iteration, but we only have to perform that operation once. After that, our time is cut down to almost nothing for primes less than our first number (since it's just a lookup), and it is very fast for primes that are just a bit bigger than our first one (since we have already done most of the work).
EDIT: Updated search for existing primes using a variation on a Binary Search Algorithm. It cut the search time at least in half.
import java.util.Scanner;
class Testing
{
public static void main(String Ar[])
{
int a = 0, i, j;
Scanner in = new Scanner(System.in);
a = in.nextInt();
for (j = a + 1;; j++)
{
for (i = 2; i < j; i++)
{
if (j % i == 0)
break;
}
if (i == j)
{
System.out.println(j);
break;
}
}
}
}
Here is the perfect code for finding next prime for a given number.
public class NextPrime
{
int nextPrime(int x)
{
int num=x,j;
for( j=num+1;;j++)
{
int count=0;
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
//System.out.println("entered");
}
//System.out.println(count);
}
if(count==2)
{
System.out.println(" next prime is ");
break;
}
}return j;
}
public static void main(String args[])
{
NextPrime np = new NextPrime();
int nxtprm = np.nextPrime(9);
System.out.println(nxtprm);
}
}
//I hope the following code works exactly.
import java.util.Scanner;
public class NextPrime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a positive integer number : ");
int n = scanner.nextInt();
for (int x = n + 1;; x++) {
boolean isPrime = true;
for (int i = 2; i < x / 2; i++) {
if (x % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("Next prime is : " + x);
break;
}
}
}
}

Manually converting a string to an integer in Java

I'm having string consisting of a sequence of digits (e.g. "1234"). How to return the String as an int without using Java's library functions like Integer.parseInt?
public class StringToInteger {
public static void main(String [] args){
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public int myStringToInteger(String str){
/* ... */
}
}
And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers, if the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
If the standard libraries are disallowed, there are many approaches to solving this problem. One way to think about this is as a recursive function:
If n is less than 10, just convert it to the one-character string holding its digit. For example, 3 becomes "3".
If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit. Recursively get a string for the first digits, then append the appropriate character for the last digit. For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".
You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.
Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)
Hope this helps!
Use long instead of int in this case.
You need to check for overflows.
public static int StringtoNumber(String s) throws Exception{
if (s == null || s.length() == 0)
return 0;
while(s.charAt(0) == ' '){
s = s.substring(1);
}
boolean isNegative = s.charAt(0) == '-';
if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
s = s.substring(1);
}
long result = 0l;
for (int i = 0; i < s.length(); i++){
int value = s.charAt(i) - '0';
if (value >= 0 && value <= 9){
if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
throw new Exception();
}else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
throw new Exception();
}
result = 10 * result + value;
}else if (s.charAt(i) != ' '){
return (int)result;
}
}
return isNegative ? -1 * (int)result : (int)result;
}
Alternate approach to the answer already posted here. You can traverse the string from the front and build the number
public static void stringtoint(String s){
boolean isNegative=false;
int number =0;
if (s.charAt(0)=='-') {
isNegative=true;
}else{
number = number* 10 + s.charAt(0)-'0';
}
for (int i = 1; i < s.length(); i++) {
number = number*10 + s.charAt(i)-'0';
}
if(isNegative){
number = 0-number;
}
System.out.println(number);
}
Given the right hint, I think most people with a high school education can solve this own their own. Every one knows 134 = 100x1 + 10x3 + 1x4
The key part most people miss, is that if you do something like this in Java
System.out.println('0'*1);//48
it will pick the decimal representation of character 0 in ascii chart and multiply it by 1.
In ascii table character 0 has a decimal representation of 48. So the above line will print 48. So if you do something like '1'-'0' That is same as 49-48. Since in ascii chart, characters 0-9 are continuous, so you can take any char from 0 to 9 and subtract 0 to get its integer value. Once you have the integer value for a character, then converting the whole string to int is straight forward.
Here is another one solution to the problem
String a = "-12512";
char[] chars = a.toCharArray();
boolean isNegative = (chars[0] == '-');
if (isNegative) {
chars[0] = '0';
}
int multiplier = 1;
int total = 0;
for (int i = chars.length - 1; i >= 0; i--) {
total = total + ((chars[i] - '0') * multiplier);
multiplier = multiplier * 10;
}
if (isNegative) {
total = total * -1;
}
Use this:
static int parseInt(String str) {
char[] ch = str.trim().toCharArray();
int len = ch.length;
int value = 0;
for (int i=0, j=(len-1); i<len; i++,j--) {
int c = ch[i];
if (c < 48 || c > 57) {
throw new NumberFormatException("Not a number: "+str);
}
int n = c - 48;
n *= Math.pow(10, j);
value += n;
}
return value;
}
And by the way, you can handle the special case of negative integers, otherwise it will throw exception NumberFormatException.
You can do like this: from the string, create an array of characters for each element, keep the index saved, and multiply its ASCII value by the power of the actual reverse index. Sum the partial factors and you get it.
There is only a small cast to use Math.pow (since it returns a double), but you can avoid it by creating your own power function.
public static int StringToInt(String str){
int res = 0;
char [] chars = str.toCharArray();
System.out.println(str.length());
for (int i = str.length()-1, j=0; i>=0; i--, j++){
int temp = chars[j]-48;
int power = (int) Math.pow(10, i);
res += temp*power;
System.out.println(res);
}
return res;
}
Using Java 8 you can do the following:
public static int convert(String strNum)
{
int result =strNum.chars().reduce(0, (a, b)->10*a +b-'0');
}
Convert srtNum to char
for each char (represented as 'b') -> 'b' -'0' will give the relative number
sum all in a (initial value is 0)
(each time we perform an opertaion on a char do -> a=a*10
Make use of the fact that Java uses char and int in the same way. Basically, do char - '0' to get the int value of the char.
public class StringToInteger {
public static void main(String[] args) {
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public static int myStringToInteger(String str) {
int sum = 0;
char[] array = str.toCharArray();
int j = 0;
for(int i = str.length() - 1 ; i >= 0 ; i--){
sum += Math.pow(10, j)*(array[i]-'0');
j++;
}
return sum;
}
}
public int myStringToInteger(String str) throws NumberFormatException
{
int decimalRadix = 10; //10 is the radix of the decimal system
if (str == null) {
throw new NumberFormatException("null");
}
int finalResult = 0;
boolean isNegative = false;
int index = 0, strLength = str.length();
if (strLength > 0) {
if (str.charAt(0) == '-') {
isNegative = true;
index++;
}
while (index < strLength) {
if((Character.digit(str.charAt(index), decimalRadix)) != -1){
finalResult *= decimalRadix;
finalResult += (str.charAt(index) - '0');
} else throw new NumberFormatException("for input string " + str);
index++;
}
} else {
throw new NumberFormatException("Empty numeric string");
}
if(isNegative){
if(index > 1)
return -finalResult;
else
throw new NumberFormatException("Only got -");
}
return finalResult;
}
Outcome:
1) For the input "34567" the final result would be: 34567
2) For the input "-4567" the final result would be: -4567
3) For the input "-" the final result would be: java.lang.NumberFormatException: Only got -
4) For the input "12ab45" the final result would be: java.lang.NumberFormatException: for input string 12ab45
public static int convertToInt(String input){
char[] ch=input.toCharArray();
int result=0;
for(char c : ch){
result=(result*10)+((int)c-(int)'0');
}
return result;
}
Maybe this way will be a little bit faster:
public static int convertStringToInt(String num) {
int result = 0;
for (char c: num.toCharArray()) {
c -= 48;
if (c <= 9) {
result = (result << 3) + (result << 1) + c;
} else return -1;
}
return result;
}
This is the Complete program with all conditions positive, negative without using library
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("error!!!");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}
Works for Positive and Negative String Using TDD
//Solution
public int convert(String string) {
int number = 0;
boolean isNegative = false;
int i = 0;
if (string.charAt(0) == '-') {
isNegative = true;
i++;
}
for (int j = i; j < string.length(); j++) {
int value = string.charAt(j) - '0';
number *= 10;
number += value;
}
if (isNegative) {
number = -number;
}
return number;
}
//Testcases
public class StringtoIntTest {
private StringtoInt stringtoInt;
#Before
public void setUp() throws Exception {
stringtoInt = new StringtoInt();
}
#Test
public void testStringtoInt() {
int excepted = stringtoInt.convert("123456");
assertEquals(123456,excepted);
}
#Test
public void testStringtoIntWithNegative() {
int excepted = stringtoInt.convert("-123456");
assertEquals(-123456,excepted);
}
}
//Take one positive or negative number
String str="-90997865";
//Conver String into Character Array
char arr[]=str.toCharArray();
int no=0,asci=0,res=0;
for(int i=0;i<arr.length;i++)
{
//If First Character == negative then skip iteration and i++
if(arr[i]=='-' && i==0)
{
i++;
}
asci=(int)arr[i]; //Find Ascii value of each Character
no=asci-48; //Now Substract the Ascii value of 0 i.e 48 from asci
res=res*10+no; //Conversion for final number
}
//If first Character is negative then result also negative
if(arr[0]=='-')
{
res=-res;
}
System.out.println(res);
public class ConvertInteger {
public static int convertToInt(String numString){
int answer = 0, factor = 1;
for (int i = numString.length()-1; i >= 0; i--) {
answer += (numString.charAt(i) - '0') *factor;
factor *=10;
}
return answer;
}
public static void main(String[] args) {
System.out.println(convertToInt("789"));
}
}

Categories

Resources