I know this will really turn out to be simple, but my brain is just not working. I need a function in C# that will return -1 if the integer passed to the function has a negative sign, return 1 if the integer has a positive sign and return 0 if the number passed is 0. So for example:
int Sign=SignFunction(-82); // Should return -1
int Sign2=SignFunction(197); // Should return 1
int Sign3=SignFunction(0); // Should return 0
This is already in the framework. Just use Math.Sign...
int sign = Math.Sign(-82); // Should return -1
int sign2 = Math.Sign(197); // Should return 1
int sign3 = Math.Sign(0); // Should return 0
In addition, it will work with:
int sign4 = Math.Sign(-5.2); // Double value, returns -1
int sign5 = Math.Sign(0.0m); // Decimal, returns 0
// ....
int sign = Math.Sign(number);
It already exists.
public int SignFunction(int number)
{
return number.CompareTo(0);
}
public int SignFunction( int input )
{
if( input < 0 ) return -1;
if( input > 0 ) return 1;
return 0;
}
return input.CompareTo(0);
public int SignFunction(int number) {
return (number > 0) ?
1 : (number < 0) ?
-1 : number;
}
If Math.Sign did not exist, I would do this:
return x == 0 ? 0 : x / Math.Abs(x);
public int Sign(int number)
{
if(number==0)
return 0;
return number/Math.Abs(number);
}
Related
I am looking for a relatively simple way to convert an integer value, which is guaranteed to be between 0 and 100, to it's decimal percentage equivalent. What I mean is if I were to have a number like 33, I would want to add a zero and a decimal place in front of it, so it would become 0.33(33%).
Here is what I have as a solution so far:
static void Main( string[] args )
{
int number = 33;
Console.WriteLine(ConvertToPercent(number));
Console.Read();
}
private static double ConvertToPercent(int value)
{
if (value >= 100)
{
return 1.0D;
}
if (value <= 0)
{
return 0.0D;
}
return Double.Parse("0." + value);
}
Is there a better, more performant way to do this using existing .NET functionality?
EDIT:
My final solution to this problem in a single method:
public static double ConvertToPercent( int value )
{
return ( double )( ( value < 0 ) ? 0 : ( value > 100 ) ? 100 : value ) / 100;
}
Try this:
decimal dec = (decimal)number / 100;
Instead of Double.Parse you can try just (decimal)value * 0.01m. The rest is fine.
I need to check if an integer has 6 characters, and if it does, remove the first three characters and return the resultant integer. Otherwise, just return the original integer. This is what i have, I would like to know if there is a better/faster/more efficient way in C#?
public static int MyMethod(int originalInt)
{
int outputInt = originalInt;
string temp = originalInt.ToString();
if (temp.Length == 6)
{
temp = temp.Substring(3);
if (!Int32.TryParse(temp, out outputInt))
{
outputInt = originalInt;
}
}
return outputInt;
}
Why use strings at all?
if (originalInt >= 100000 && originalInt < 1000000)
return originalInt % 1000;
return originalInt;
(Assuming originalInt is always positive)
Try This :
public static int MyMethod(int originalInt)
{
return (originalInt > 99999 && originalInt <1000000)?originalInt % 1000 : originalInt;
}
It returns the result that you need
I am trying to convert decimal to hexadecimal. I have found many codes online. I used
int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
but my instructor told me I can't use any of those, just use recursive method. I am new to programming and little confused about recursive method.
I did find other methods to convert it, I am using below method, and I used switch statement to change numbers to letters. Program works fine. But not sure if it is recursive method? Can someone let me know if it is recursive method, if not help me understand how recursive method work.
static void HexadecimalConversion(int decimals)
{
if (decimals == 0)
return;
else
{
int hexadecimals = decimals % 16;
decimals = decimals / 16;
HexadecimalConversion(decimals);
With most recursive problems, you have 1 or 2 special cases and a general case. For this problem there are 3 cases:
Special Case #1. The value to be converted is 0.
The General Case. The value to be converted is greater than 0.
The Terminating Case. When the value to be converted is finally decremented to 0.
You need to distinguish between the two 'zero' conditions, lest you always append a trailing zero to the result, so...you need a 2-layered approach, something like this:
static string Int2Hex( int value )
{
if ( value < 0 ) throw new ArgumentOutOfRangeException("value") ;
if ( value == 0 ) return "0" ;
string result = ToHex( (uint) value ).ToString() ;
return result ;
}
static StringBuilder ToHex ( uint value )
{
StringBuilder buffer ;
if ( value <= 0 )
{
buffer = new StringBuilder() ;
}
else
{
buffer = ToHex( value / 16 ).Append( "0123456789ABCDEF"[ (int)(value % 16 ) ] ) ;
}
return buffer ;
}
Yet another implementation:
public string ConvertToHexa(int number)
{
if (number == 0)
return String.Empty;
var head = ConvertToHexa(number / 16);
var remainder = number % 16;
var tail = (char)(remainder + (remainder >= 10 ? 'A' - 10 : '0'));
return head + tail;
}
Console.WriteLine(ConvertToHexa(202)) gives "CA" (which is correct).
Another implementation
public void ConvertToHexa(int number)
{
if (number == 0)
return;
ConvertToHexa(number / 16);
var remainder = number % 16;
Console.Write(remainder >= 10 ? ((char)(remainder - 10 + 'A')).ToString() : remainder.ToString());
}
I have 2 decimal values: a and b. How do I use bit operator to check if two value is same sign?
You can use Math.Sign(). When you use Math.Sign(x), if x is negative it returns -1 else if its positive, the function returns 1 or when its 0 it returns 0. So :
if(Math.Sign(a) == Math.Sign(b))
{
// Code when sign matched.
}
else
{
// Code when sign not matched.
}
Do you mean if both are positive or both are negative?
bool bothSameSign = (d1 >= 0 && d2 >= 0) || (d1 < 0 && d2 < 0);
I don't think you really need to use the bit operator for this, but if for some reason you must (e.g. this is a school question):
Firstly you can use Decimal.GetBits() get all the bits in the two Decimals to compare, as an array of 4 ints.
Then you can inspect the sign bit which is at bit 31 in the int at offset 3 in the array of ints.
Decimal d1 = 1;
Decimal d2 = -1;
var bits1 = Decimal.GetBits(d1);
var bits2 = Decimal.GetBits(d2);
const int signMask = 1 << 31;
const int signWord = 3;
bool sameSign = ((bits1[signWord] & signMask) == (bits2[signWord] & signMask));
You could make,
static int Sign(this decimal value)
{
return Decimal.GetBits(value)[3] & 0x8000;
}
and do
a.Sign == b.Sign;
Bitwise shift is required for the sign-checking you want to accomplish:
if ( ( number >> sizeof(byte) * sizeof(numberType) -1 ) & 1)
{ /* < 0 */ }
else
{ /* >= 0 */ }
// you can of course use magic numbers
// example for int: if ( ( number >> 31 ) & 1) { /* < 0 */ }
Problem is, you can't bitshift a decimal. You would have to do something like this:
var shiftableNumber = Int.Parse(Math.Truncate(yourDecimal));
I can't verify it, but I suspect it would defeat the purpose of optimizing through bitwise operators. You might aswell use the builtin Math.Sign() directly.
Is That Any calculation or method allow me to check whether a double value is Int or Double in c# code
Example
Double NumberOne = 55.00 // Return False
Double NumberTwo = 55.10 // Return True
Use Math.Floor
if (Math.Floor(number) == number) {
// yay, an "int"
}
private bool IsDoubleNotAnInt(double num)
{
if ((num % 1) == 0)
{
return false;
}
else
{
return true;
}
}
You could check
n % 1 == 0
to determine this.
You could compare it with value without fractional part:
Math.Floor(n) != n