How to count total number of chars in float number - java

Could you help me to write a method with the following signature:
public int method(double value)
that returns total number of chars in value(including the decimal point), for example:
method(5.0) - 3
method(1.2345) - 6
method(2.34) - 4
The problem is that method(5) must return 1, not 3, looking at 5 as it is 5.0

Change the value argument to string and find its length as follow:
String valueString = value+"";
int count = valueString.length()
Do this inside your method()
Update:
public static int method(double value){
String temp;
if(value == (long) value)
temp = String.format("%d",(long)value);
else
temp = String.format("%s",value);
return temp.length();
}
--
Input: 5.01 gives Output: 4
Input: 5.0 gives Output: 1

First , convert the double to string, and then calculate its size.
String str = String.valueOf(yourDoubleNumber);
int charCount = str.length();
it will give you the size of string i.e character count

Doubles and floats don't have chars. They have bits. If you're asking about decimal digits, you would first have to convert to a decimal radix.

int method(double value) {
if (value == (int) value)
return Integer.toString((int)value).length();
else return Double.toString(value).length();
}

Overload your method with an int argument method, and then apply your logic as before.
public int method(double d){
//your logic
}
public int method(int i){
//your logic
}`enter code here

Related

Rounding integers to one significant digit

I want to round down an int in Java, what i mean is, if I have an int 45678, i want to convert that int into 40000
this is how im calling it
int den = placeValue(startCode,length);
and this is the code
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
so if i have 89765, i would want 80000,
but instead it return the place value of whatever length is.
So,
for 89765, the length would be 5, so the return value is 5 i.e. the value in the ones place.
but if the number was 85760
then it would return 5000.
I hope that makes sense.
Any suggestions would be much appreicated.
In my opinions, if I can avoid 'calculating' I will compute the answer from other concept since I am not confidence on my math (haha).
Here is my answer. (only work in positive numbers)
I think the length of the inputted number is not necessary.
static int placeValue2(int N) {
String tar = N+"";
String rtn = tar.substring(0,1); // take first digital
for (int i=0;i<tar.length()-1;i++) // pad following digitals
rtn+="0";
return Integer.parseInt(rtn);
}
I appreciate you asked the question here.
Here is my solution. I don't know why you are taking two parameters, but I tried it from one param.
class PlaceValue{
int placeValue(int num){
int length = 0; int temp2=1;
boolean result=false;
long temp1=1;
if (num<0){
result=true;
num=num*(-1);
}
if (num==0){
System.out.println("Value 0 not allowed");
return 0;
}
while (temp1 <= num){ //This loop checks for the length, multiplying temp1 with 10
//untill its <= number. length++ counts the length.
length++;
temp1*=10;
}
for (int i=1; i<length; i++){//this loop multiplies temp2 with 10 length number times.
// like if length 2 then 100. if 5 then 10000
temp2=temp2*10;
}
temp2=(num/temp2)*temp2;
/* Let's say number is 2345. This would divide it over 1000, giving us 2;
in the same line multiplying it with the temp2 which is same 1000 resulting 2000.
now 2345 became 2000;
*/
if (result==true){
temp2=temp2*(-1);
}
return temp2;
}
}
Here is the code above. You can try this. If you are dealing with the long numbers, go for long in function type as well as the variable being returned and in the main function. I hope you understand. otherwise, ask me.
Do you want something like this?
public static int roundDown(int number, int magnitude) {
int mag = (int) Math.pow(10, magnitude);
return (number / mag) * mag;
}
roundDown(53278,4) -> 50000
roundDown(46287,3) -> 46000
roundDown(65478,2) -> 65400
roundDown(43298,1) -> 43290
roundDown(43278,0) -> 43278
So the equivalent that will only use the most significant digit is:
public static int roundDown(int number) {
int zeros = (int) Math.log10(number);
int mag = (int) Math.pow(10, zeros);
return (number / mag) * mag;
}

Java program that converts binary numbers to decimal numbers. The input is a string of zeros and ones

I have to create a java program that converts binary to decimal using the following steps. Being new at this I did something, but I don't know what I did wrong or how to continue.
public class BinaryToDecimal {
public static void main(String args[]){
long sum = 0;
int result;
String s = "1001010101011010111001011101010101010101";
for(int i = s.length()-1; i <= 0; i--){
result = (int)Math.pow(2, i);
if(s.charAt(i) == '1')
sum=sum + result;
}
System.out.println(sum);
}
}
Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left;
Use the loop to build the required powers of 2;
Use a conditional statement to deal with 0 and 1 separately;
Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.
Use your program to find the decimal value of the following binary number:
1001010101011010111001011101010101010101
Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. If you don't know, just check the length of your string. If it's less than or equal to 32 i.e. 4 bytes, then you can use parseInt.:
int decimalValue = Integer.parseInt(s, 2);
Refer HERE for more info on the Integer.parseInt();
But if it's more, you can use your code. I modified your loop which is where your problem was:
String s = "1001010101011010111001011101010101010101";
long result = 0;
for(int i = 0; i < s.length(); i++){
result = (long) (result + (s.charAt(i)-'0' )* Math.pow(2, s.length()-i-1));
}
System.out.println(result);
The first thing I notice is that your binary number has more than 32 bits. This cannot be represented in the space of an int, and will result in overflow.
As a simpler answer, I ran the following and got the correct value at the end, it just uses simple bit shifts.
For each index in the string, if the character is 1, it sets the corresponding bit in the result.
public class BinaryToDecimal {
public static void main(String[] args) {
long sum;
String bin = "1001010101011010111001011101010101010101";
sum = 0;
for (int i = 0; i < bin.length(); i++) {
char a = bin.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
}
sum >>= 1;
System.out.println(sum);
}
}
The loop runs from i = s.length()-1 until i <= 0. This should be i>=0.
The next problem is "int result". It works fine with result as a long ;) (Reason: You calculate a 40-bit value at the MostSignificantBit, but Integers only use 32-bit)
Also: You start at the rightmost Bit with i=s.length()-1. But the power that you calculate for it is 2^(s.length()-1) though it should be 2^0=1.
The solution is: result = (long)Math.pow(2, s.length()-1-i)
Edit:
I really like the solution of user2316981 because of its clear structure (without Math.pow, should be faster by using shift instead). And loops from 0 to MSB as I do with Double&Add algorithm. Can't comment on it yet, but thanks for the reminder ;)
import java.util.*;
import java.lang.Math;
class deci {
int convert(int n) {
int tem=1,power=0;
int decimal=0;
for (int j=0;j<n;j++) {
if(n==0) {
break;
} else {
while(n>0) {
tem=n%10;
decimal+=(tem*(Math.pow(2,power)));
n=n/10;
power++;
}
}
}
return decimal;
}
public static void main(String args[]) {
System.out.print("enter the binary no");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
deci dc=new deci();
int i=dc.convert(n);
System.out.print(i);
}
}

How can I rewrite this to not have the Type mismatch error?

How do I rewrite this code to not have the Type Mismatch error on return Math.abs(i);
public static int[] countDigits(Scanner input) {
int[] count = new int[10];
int i = input.nextInt();
while (Math.abs(i) >= 10 ) {
i = i / 10;
}
return Math.abs(i);
This is the segment of code in particular that I need help with.It Reads integers from input, computing an array of counts for the occurrences of each leading digit (0-9).
Change your return type from int[] to int... because Math.abs returns one Integer. Not an array of Integers. Like this
public static int countDigits(Scanner input)

Gets last digit of a number

I need to define the last digit of a number assign this to value.
After this, return the last digit.
My snippet of code doesn't work correctly...
Code:
public int lastDigit(int number) {
String temp = Integer.toString(number);
int[] guess = new int[temp.length()];
int last = guess[temp.length() - 1];
return last;
}
Question:
How to solve this issue?
Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.
If number can be negative then use (Math.abs(number) % 10);
Below is a simpler solution how to get the last digit from an int:
public int lastDigit(int number) { return Math.abs(number) % 10; }
Use
int lastDigit = number % 10.
Read about Modulo operator: http://en.wikipedia.org/wiki/Modulo_operation
Or, if you want to go with your String solution
String charAtLastPosition = temp.charAt(temp.length()-1);
No need to use any strings.Its over burden.
int i = 124;
int last= i%10;
System.out.println(last); //prints 4
Without using '%'.
public int lastDigit(int no){
int n1 = no / 10;
n1 = no - n1 * 10;
return n1;
}
You have just created an empty integer array. The array guess does not contain anything to my knowledge. The rest you should work out to get better.
Your array don't have initialization. So it will give default value Zero.
You can try like this also
String temp = Integer.toString(urNumber);
System.out.println(temp.charAt(temp.length()-1));
public static void main(String[] args) {
System.out.println(lastDigit(2347));
}
public static int lastDigit(int number)
{
//your code goes here.
int last = number % 10;
return last;
}
0/p:
7
Use StringUtils, in case you need string result:
String last = StringUtils.right(number.toString(), 1);
Another interesting way to do it which would also allow more than just the last number to be taken would be:
int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;
int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>
In the above example if n was 1 then the program would return: 4
If n was 3 then the program would return 454
here is your method
public int lastDigit(int number)
{
//your code goes here.
int last =number%10;
return last;
}
Although the best way to do this is to use % if you insist on using strings this will work
public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}
but I just wrote this for completeness. Do not use this code. it is just awful.

Java Convert integer to hex integer

I'm trying to convert a number from an integer into an another integer which, if printed in hex, would look the same as the original integer.
For example:
Convert 20 to 32 (which is 0x20)
Convert 54 to 84 (which is 0x54)
The easiest way is to use Integer.toHexString(int)
public static int convert(int n) {
return Integer.valueOf(String.valueOf(n), 16);
}
public static void main(String[] args) {
System.out.println(convert(20)); // 32
System.out.println(convert(54)); // 84
}
That is, treat the original number as if it was in hexadecimal, and then convert to decimal.
Another way to convert int to hex.
String hex = String.format("%X", int);
You can change capital X to x for lowercase.
Example:
String.format("%X", 31) results 1F.
String.format("%X", 32) results 20.
int orig = 20;
int res = Integer.parseInt(""+orig, 16);
You could try something like this (the way you would do it on paper):
public static int solve(int x){
int y=0;
int i=0;
while (x>0){
y+=(x%10)*Math.pow(16,i);
x/=10;
i++;
}
return y;
}
public static void main(String args[]){
System.out.println(solve(20));
System.out.println(solve(54));
}
For the examples you have given this would calculate: 0*16^0+2*16^1=32 and 4*16^0+5*16^1=84
String input = "20";
int output = Integer.parseInt(input, 16); // 32
The following is optimized iff you only want to print the hexa representation of a positive integer.
It should be blazing fast as it uses only bit manipulation, the utf-8 values of ASCII chars and recursion to avoid reversing a StringBuilder at the end.
public static void hexa(int num) {
int m = 0;
if( (m = num >>> 4) != 0 ) {
hexa( m );
}
System.out.print((char)((m=num & 0x0F)+(m<10 ? 48 : 55)));
}
Simply do this:
public static int specialNum(num){
return Integer.parseInt( Integer.toString(num) ,16)
}
It should convert any special decimal integer to its hexadecimal counterpart.

Categories

Resources