I am trying to pick the even digits from a number and convert them to odd by adding 1 to it
example input/output
n = 258463, ans = 359573
int n=26540;
System.out.println("n= "+n+", ans= "+even2odd(n));
n=9528;
System.out.println("n= "+n+", ans= "+even2odd(n));
public static int even2odd(int n)
{
while ( n > 0 ) {
if (n%2==0) {
n +=1;
}
System.out.print( n % 10);
n = n / 10;
}
int ans = n;
return ans;
}
as you can see right I managed to convert all the even digits to odd but i dont know how to reverse them back into order and output it in the right place
Aaaaaannnd one liner goes here
int i = Integer.parseInt(Integer.toString(26540).replaceAll("2", "3").replaceAll("4", "5").replaceAll("6", "7").replaceAll("8", "9"));
You can do this:
public static int even2odd(int n)
{
StringBuilder result = new StringBuilder();
while(n > 0)
{
int firstDigit = n %10;
if(firstDigit%2==0)
++firstDigit;
result.append(firstDigit);
n = n/10;
}
return Integer.parseInt(result.reverse().toString());
}
How about:
String numString = n+"";
String outString = "";
for(int i=0; i<numString.length;i++){
int digit = Character.getNumericValue(numString.charAt(i));
if(digit%2==0) digit++;
outString+=digit;
}
int out = Integer.parseInt(outString);
If you are instructed not to use String or Integer.
public static int even2odd(int n) {
int ans = 0;
int place = 1;
while ( n > 0 ) {
if (n%2==0) {
n +=1;
}
ans = ans+((n%10)*place);
place = place*10;
n = n / 10;
}
System.out.print( ans);
return ans;
}
Related
public class Binar{
public static void main(String[] args){
int num = 7;
long Binary = cBtD(num);
System.out.printf("%d numri decimal = %d binar" , num, Binary);
}
public static long cBtD(int num){
long BinaryNumber = 0;
int i = 0;
long reminder;
while(num > 0){
reminder = num % 2;
num /= 2;
++i;
}
for (int j = i - 1; j >= 0; j--) {
System.out.print(BinaryNumber[j]);
}
return BinaryNumber;
}}
and i have this error and it says "array required, but long found" and "System.out.print(BinaryNumber[j]);"
Reason behind this error is, you have defined BinaryNumber variable as long and it is not an array. But you are trying to access it like an array. Please check my modified answer below:
public class Binar {
public static void main(String[] args) {
int num = 7;
String Binary = cBtD(num);
System.out.printf("%d numri decimal = %s binar", num, Binary);
}
public static String cBtD(int num) {
String BinaryNumber = "";
long reminder;
if (num == 0) {
return "0";
}
while (num > 0) {
reminder = num % 2;
BinaryNumber = String.valueOf(reminder).concat(BinaryNumber);
num /= 2;
}
return BinaryNumber;
}
}
That error occurred because you defined BinaryNumber's type 'long' and you wanted use it as an array.
I change it a bit, try it:
public class Binar {
public static void main(String[] args) {
int num = 7;
int[] binaryArray = cBtD(num);
String numbers = "";
for (int aBinaryArray : binaryArray)
numbers += aBinaryArray;
System.out.printf("%d numri decimal = %d binar" , num, Integer.parseInt(numbers));
}
private static int[] cBtD(int num){
int i = 0;
int temp[] = new int[7];
int binaryNumber[];
while (num > 0) {
temp[i++] = num % 2;
num /= 2;
}
binaryNumber = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binaryNumber[k++] = temp[j];
}
return binaryNumber;
}
}
Or you can simply use these methods to convert decimal to binary:
Integer.toBinaryString();
Or this:
Integer.toString(n,2);
All numbers are inherently binary. But whether you display them in binary or hex or octal is simply a matter of representation. Which means you want to print them as a string. Even when you do the following:
int v = 123;
System.out.println(v); // v is printed as a decimal string.
So to convert them to a binary string, just prepend the remainders to the string after dividing by two (via the remainder operator).
int n = 11;
String s = "";
s = (n%2) + s; // s = "1"
n/=2; // n == 5
s = (n%2) + s; // s = "11"
n/=2 // n == 2
s = (n%2) + s; // s = "011";
n/=2 // n == 1
s = (n%2) + s; // s = "1011";
n/=2; // n == 0
n == 0 so your done.
return s and print it.
How can I convert int=43707 to two other numbers?
The first number is made by value of odd bits. Second number is made by value of even bits.
int x = 43707; // 1010101010111011
var even = 0;
var odd = 0;
for (int i = 0; i<=31; i++) {
if(i%2 == 0) {
?
} else {
?
}
}
Your looking for the bitwise AND operation: &. you can use it together with a binary mask (normally specified in hex notation 0x00FF). so you need to do something like:
int x= 707; //10110011
int oddBits = 0x5555; //01010101
int evenBits = 0xAAAA; //10101010
int oddResult = x & oddBits;
System.out.println(oddResult);
int evenResult = x & evenBits;
System.out.println(evenResult);
which returns: 65 //00010001
and 642 // 10100010
Just convert int into digits as shown below:
List<Integer> digits = new ArrayList<Integer>();
while(x > 0) {
digits.add(x % 10);
x /= 10;
}
System.out.println(digits);
Once you have the separated the digits then apply the even odd logic. Here is complete code:
int x = 43707; // 1010101010111011
List<Integer> digits = new ArrayList<>();
while(x > 0) {
digits.add(x % 10);
x /= 10;
}
int i = 0;
int length = digits.size();
while (i < length) {
if(digits.get(i)%2 == 0){
System.out.println("Even Number" + digits.get(i));
} else {
System.out.println("Odd Number" + digits.get(i));
}
i++;
}
If you are looking for the Binary conversion then you can use the below code.
int x = 43707; // 1010101010111011
int testNumber;
String binaryNumber = Integer.toBinaryString(x);
for (int i = 0 ; i != binaryNumber.length() ; i++) {
char c = binaryNumber.charAt(i);
testNumber = Character.getNumericValue(binaryNumber.charAt(i));
if(testNumber == 0){
System.out.println("Even Number");
} else {
System.out.println("Odd Number");
}
System.out.println(c);
}
System.out.println(binaryNumber);
It converts the Int to Binary and then check even and odd numbers.
Hope, it works for you as per your desired output.
I came up to this:
int x = 43707;
String binary = Integer.toBinaryString(x);
System.out.println("binary=" + binary);
String odds = "";
String evens = "";
for (int i = binary.length() - 1; i >= 0; i--) {
if ((i + 1) % 2 == 0) {
odds += binary.charAt(i);
} else {
evens += binary.charAt(i);
}
}
System.out.println("odds=" + odds);
System.out.println("evens=" + evens);
int odd = Integer.parseInt(odds, 2);
int even = Integer.parseInt(evens, 2);
System.out.println("number from odd bits=" + odd);
System.out.println("number from even bits=" + even);
prints
binary=1010101010111011
odds=10100000
evens=11111111
number from odd bits=160
number from even bits=255
I'm counting right to left the bits.
I have an int that ranges from 0-99. I need to get two separate ints, each containing one of the digits. I can't figure out how to get the second digit. (from 64 how to get the 6) This is my code:
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
//????
}
}
return n;
}
You can do integer division by 10. For example, in the following code res should equal 4:
int res = 42 / 10;
Simply divide by 10.
...
if(index) {
n = pos/10;
}
...
Simple: in order to get any leading digit; just create a loop; and during each run, divide by 10.
In your case, you can even omit the loop ;-)
you can do:
if(index){
return x % 10;
}
return x / 10;
or maybe a little something
public int getNumber(....){
return index ? x % 10 : x / 10;
}
Just divide the number by 10. If it's int, the result will be int.
class Main {
public static void main(String[] args) {
int a = 8;
int b = 28;
int c = 99;
System.out.println(a / 10);
System.out.println(b / 10);
System.out.println(c / 10);
}
}
Here is a trick. Replace your //???? with below code.
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
Complete code should look like,
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
}
}
return n;
}
Scanner scan = new Scanner(System.in);
System.out.println("Give a number");
int n = scan.nextInt();
int secondNumber = 0;
while (n > 9) {
secondNumber= n % 10;
n /= 10;
}
to find the first number you need to add to while a constant = n/10; (firstNumber = n / 10;)
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);
}
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"));
}
}