I have upload this code already but it was having some problems and now I have update my code this program does not provide me exact reverse number when I enter 123 it return me 321 but if I enter 001 or 100 it just return me 1 in both case help me to solve this issue
public class Employee {
void fun(int choice) {
int number = choice;
int remander = 0;
int reverse = 0;
while (number >= 1) {
remander = number % 10;> taking remainder here
reverse = reverse * 10 + remander;
number = number / 10;
}
System.out.println(reverse);
}
public static void main(String args[]) {
Employee ob=new Employee();
int choice;
System.out.println("Enter number you want to return");
Scanner obj=new Scanner(System.in);
choice= obj.nextInt();
ob.fun(choice);
}
}
`
Here's a one-liner you can use to convert int to Stream of String numbers, reverse it and return as a String:
Stream.of(Integer.toString(choice).split("")).reduce((c1,c2)->c2+c1).get();
First point: be careful about adding leading 0s to the number. If the number is an integer literal, the leading 0s will actually cause the integer to be interpreted as octal. In this case, 001 octal does, in fact, equal 1 in decimal too, but only due to luck. If you picked another number, it would not give you the result you're expecting; for example, the following code actually prints 63 (not 77):
public class HelloWorld{
public static void main(String []args){
int x = 0077;
System.out.println(x);
}
}
On the other hand, if you're parsing an integer out of a string or using a scanner, the leading 0s will simply be stripped off. For example, the following prints 77:
System.out.println(Integer.parseInt("0077"));
Unfortunately, in neither case will you get 0077, so the leading 0s won't make any difference when you go to do the reverse operation.
Also, think about what happens for 100:
reverse = reverse * 10 + remander;
Reverse is 0 to start with (and 0 * 10 == 0) and 100 % 10 == 0 because 100 is evenly divisible by 10. Put another way, the statement is equal to:
reverse = 0 * 10 + 0;
which clearly equals 0.
You can't do this using Scanner.nextInt() because there is no way to tell if leading zeroes were included once they are converted to an int. And the octal situation is not relevant since Scanner does not process ints that way. So you use either an all String solution and verify the characters are digits or use a hybrid of both math and String methods. I did the latter. The following:
reads in a String
converts to an int
calculates the number of leading zeroes by using the log10 of the
int and the length of the entered string.
Allocates a StringBuilder to hold the result.
Scanner input = new Scanner(System.in);
String val = input.nextLine();
int numb = Integer.valueOf(val);
int len = val.length();
// exponent of the entered number rounded up to the next int.
// This computes the number of digits in the actual int value.
int exp = (int) Math.log10(numb) + 1;
// now reverse the integer and store in the StringBuilder
StringBuilder sb = new StringBuilder();
while (numb > 0) {
sb.append(numb % 10);
numb /= 10;
}
// and append the leading zeros.
System.out.println(sb + "0".repeat(len - exp));
for input of 00001000
prints 00010000
Note that you are still constrained on input by Integer.MAX_VALUE.
Related
I'm 100% new to java. Cannot use string or "breaks" or arrays to solve the problem. Any feedback is great :)
Roadmap is:
Name the number from the user input.
Declare and initialize a counter variable to zero.
Save the right-most digit of input in a variable using the modulo
operator: rightMost = input % 10
Update the value of input = input/10
Determine if the rightMost digit is odd. Use a divisibility test using the modulo operator %.
if rightMost is odd, increase the counter by 1.
if rightMost is even, do nothing.
if the input is not zero, go to step 3.
if the input is zero, the program has reached the last digit and it needs to go to step 10.
Display the results. the counter will have the value of the number of odd digits in the original number.
My code is below: (I probably haven't made it far, but I'm trying)( i likely might need to do a while or do while method)( any guide that has !, =< as a list would be appreciative)
import java.util.Scanner;
public class Labtwo
{
public static void main(String[] args)
{
System.out.print("Please enter an integer:");// program lets user know to input a number
// allow keyboard access for user
// likely in a while or do while method?
Scanner kbd = new Scanner(System.in); // allows user input labels it as kbd
int input = kbd.nextInt();// kbd new value is input as a integer
//int counter = 0;
int rightMosteven= 0;
int rightMostodd = 0;
while (input > 0){
int rightMost = (input % 10);
if(rightMost%2==0)
rightMosteven ++;
else
rightMostodd++;
input=input/10;
}
System.out.printf("Number of odd digits: "+ rightMostodd);
//System.out.printf("Number of even digits: "+ rightMosteven);
}
}
This is my new code updated im just not sure if == is considered a string if it is then my answer is 0 as stated by the "cannot use section"
This answer assumes that you want to count the number of odd digits which some input number has. In fact, using the modulus is one viable way to do this. Consider this version:
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int counter = 0;
while (input > 0) {
if (input % 2 != 0) {
++counter;
}
input /= 10;
}
Here is a breakdown of what would happen for an example input of 12345:
1234 => last digit even, counter = 0
divide input by 10
123 => last digit odd, counter = 1
divide input by 10
12 => last digit even, counter = 1
divide input by 10
1 => last digit odd, counter = 2
divide input by 10
0 => terminate while loop
The problem statement is :
Problem Statement-: Altaf has recently learned about number bases and is becoming fascinated.
Altaf learned that for bases greater than ten, new digit symbols need to be introduced, and that the convention is to use the first few letters of the English alphabet. For example, in base 16, the digits are 0123456789ABCDEF. Altaf thought that this is unsustainable; the English alphabet only has 26 letters, so this scheme can only work up to base 36. But this is no problem for Altaf, because Altaf is very creative and can just invent new digit symbols when she needs them. (Altaf is very creative.)
Altaf also noticed that in base two, all positive integers start with the digit 1! However, this is the only base where this is true. So naturally, Altaf wonders: Given some integer N, how many bases b are there such that the base-b representation of N starts with a 1?
Input Format :
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of one line containing a single integer N (in base ten).
Output Format :
For each test case, output a single line containing the number of bases b, or INFINITY if there are an infinite number of them.
Constraints:
1 <= T <= 10^5
0 <= N < 10^12
Sample Input
4
6
9
11
24
Sample Output:
4
7
8
14
Explanation:
In the first test case, 6 has a leading digit 1 in bases 2, 4, 5 and 6: 610 = 1102 = 124 = 115 = 106.
I trying this in java , But at some point my loop is not working it only takes the first value and after that it will come out of the loop!! Thank you
My code :
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long n,i,j,k,m;
long count=0,rem1,index;
long rem[];
rem = new long[(int)100];
int t = sc.nextInt();
for(i=1;i<=t;i++)
{
n = sc.nextInt();
j=2;
while(j<=n)
{
// for(j=2;j<=n;j++)
// {
index=0;
m = j;
while(n>0)
{
rem1 = n%m;
rem[(int)index++] = rem1;
n = (long) (n / m);
}
// for(k=index-1;k>=0;k--)
// {
if(rem[1]==1)
{
count++;
}
// }
j++;
}
System.out.println(count);
// }
}
}
}
I'm not sure I follow the logic in the loop (and, by your own admission, there's a problem there).
The logic of the loop (i.e., "how many bases represent the number N with a representation starting by 1"), can be greatly simplified.
The first step is finding the highest power of the base B required to represent the number N. This is given by logb(n), truncated to the nearest integer. Java doesn't have a built-in log function with a variable base, but you can get this result by calculating log(n)/log(b).
Then, you need to find the digit in this position. This can be calculated by dividing N by Bpower using integer division.
From there on, you just need to check if the result is 1, and if so, record it.
Put it all together and you'll end up with something like this:
private static int howManyBasesStartWithOne(int num) {
int count = 0;
for (int i = 2; i <= num; ++i) {
int highestBase = (int) (Math.log(num) / Math.log(i));
int leadingDigit = num / (int) Math.pow(i, highestBase);
if (leadingDigit == 1) {
++count;
}
}
return count;
}
Is there a way to convert an int to binary number without using Integer.toBinaryString method?
I tried to figure out the algorithm for the conversion but haven't had any luck with it.
My task is this: (https://open.kattis.com/problems/reversebinary)
Insert an Int with help of Scanner.
Convert the Int to binary.
Reverse the binary.
Print out the new Int.
For example, the number 11 is 1011 in binary.
Now reverse the binary number 1011 and you get 1101 (which is the number 13)
and print out 13.
This is what I got, but still, I used the Integer.toBinaryString method and I get NumberFormatException.
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toString(number, 2);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
}
First of all, you should use the correct terms. You are not converting an int to a binary. The int type (as well as all numeric types) are already stored in a binary format. When you convert an int to a String, or a String to an int, you choose the radix that the String representation uses (such as decimal, binary, octal, hexadecimal, etc..). This determines the digits that appear in the String representation. Now, based on your example, what you wish to do is generate a number whose binary representation is the reverse of the input number. In other words, you want to reverse the bits of the input number.
Your current loop :
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
calculates the decimal (radix 10) digits of binary and creates an integer whose value is the value of those digits when they are arranged in reversed order.
If you want the reverse of the binary representation of the input number, you should multiply and divide by 2 in order to obtain the binary digits (aka bits) of the input number and reverse them :
while (number != 0) {
System.out.print (number % 2); // prints a binary digit (i.e. 0 or 1)
reverse = reverse * 2 + number % 2;
number = number / 2;
}
System.out.println();
System.out.println(reverse); // prints the decimal representation of the reversed number
If number is 11, reverse will be 13, since the reverse of 1011 is 1101. This code will print both the binary representation of the reversed number (1101) and the decimal representation (13).
Instead of reversing the binary as a number, reverse it while it is still a String, new StringBuilder(b).reverse().toString(). Then convert it back to an int from base 2, and you're done.
So the entire code would be:
final Scanner scn = new Scanner(System.in);
final int number = scn.nextInt();
String b = Integer.toString(number, 2);
b = new StringBuilder(b).reverse().toString();
System.out.println(Integer.parseInt(b.toString(), 2));
Maybee the smartest solution for this problem is bit shifting. I wrote an example with a little explanation.
int number, reverse = 0;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
while (number > 0)
{
// shift all bits to the left
reverse = reverse << 1;
// extract the last bit of the number
int bit = number & 1;
// add the last bit to the reverse version
reverse |= bit;
// shift alle bits to the right
number = number >> 1;
}
System.out.println(reverse);
Integer.toBinaryString - Returns a string representation of the integer argument as an unsigned integer in base 2.
String toString(int i, int radix) -
Returns a string representation of the first argument in the radix specified by the second argument
public static void main(String[] args) {
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toBinaryString(number);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
Infact whatever you use cannot give an error. The above code perfectly compiles without an error.
Providing 11, gives 13 perfectly.
How to convert binary to decimal i a have code for up to 2 power 10 i need help to 2 power 32
I have tried some other website for the program where i can change to get the appropriate answerer for my coding
{
int [] positionNumsArr= {1,2,4,8,16,32,64,128};//for up to 2 power 8 binary value
int[] numberSplit = new int [8];
Scanner scanNum = new Scanner(System.in);
int count1=0;
int decimalValue=0;
System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
int number = scanNum.nextInt();
while (number > 0)
{
numberSplit[count1]=( number % 10);
if(numberSplit[count1]!=1 && numberSplit[count1] !=0)
{
System.out.println("Was not made of only \"1\" or \"0\" The program will now restart");
main(null);
}
count1++;
number = number / 10;
}
for(int count2 = 0;count2<8;count2++)
{
if(numberSplit[count2]==1)
{
decimalValue=decimalValue+positionNumsArr[count2];
}
}
System.out.print(decimalValue);
}
}
You just need to use Long.parseLong() and specify 2 as the base. Example:
String str = "11101000101";
Long num = Long.parseLong(str, 2); // parse it in base 2, i.e., binary
System.out.print(num); // outputs 1861
This will work up to 263-1 (the max Long value).
Here's a working demo.
As a programming assignment for my java CSC class I have written the following code to convert a number and its base to a decimal number and then to a desired number and base.
public static int baseten(int number,int basein){
int power = 0;
int baseten = 0;
while (number > 0) {
int finalDigit = number % 10;
int product = finalDigit*(int)Math.pow(basein, power);
baseten += product;
number = number / 10;
power++;
}
return(baseten);
}
public static String convert (int decimal, int baseout){
String result = "";
while (decimal > 0){
//if baseout
int remainder = decimal % baseout;
decimal = decimal / baseout;
result = remainder + result;
}
return(result);
}
The question is how to convert a number to a base higher than ten within this code? I assume maybe a char[], but I'm not very good with arrays right now and can't imagine what that might look like. I don't think I can use toString's or parseInt's. Any help would be appreciated. Thanks in advance.
You are almost there. What you could do is insert an if/else statement to determine whether the remainder is greater or equal to ten or not and act accordingly. If it isn't, do what you're doing right now. If it is, then you need to add a char to your string. This char must be (remainder-10) + 65, since 65 is capital A on the ascii table and you need to know how many digits above ten remainder is and add that to A. This could be simplified to simply adding 55, but that is less readable in my opinion. Then, just add that char to the string instead of adding the int.