How can I define comparison has to be an int? - c#

Here a short code for the thing which is already coded:
if (str.Length % 3 != 0)
Now my question is, how can I define, that if str.Length % 3 = int it has to do something?
Here an example:
123456789123 / 3 = int...
I know, the Syntax I used isn't correct, but it's because I don't know how to do it.
You would also help me, if you told me, what the "opposite" of if (str.Length % 3 != 0) is.
Thanks for helping.

It will be an int no matter what with the code you have provided.
Reason: int / int = int ... any decimal values will be truncated (not rounded). C# does not automatically turn numbers into float or double if there is need for it. You need to do type conversion of that nature explicitly.
I think you may have also confused modulo % and divide /. If you want to know if there is no remainder which means that the number coming out of the computation is an Integer do the if (str.Length % 3 != 0) you put in the code.... I assume you're looking for something like this
if (str.Length % 3 != 0)
{
int num = str.Length / 3;
//Now do something with your int version of num
}
else
{
double num = str.Length / (double)3;
//Now do something with your double version of num
}
By casting 3 which is an int to double the resulting number will be a double, if you don't do that you will get a truncated integer value then implicitly casted to a double and stored in num.

The statement str.Length % 3 always results in an integer. What you need is probably just a simple negation of this statement, that will tell you, that there is a remainder...
Negation of != is of course ==

try this
if ((str.Length % 3).GetType() == typeof(int))
{
//is integer
}

Related

Converting String to Integer without using Multiplication C#

Is there a way to convert string to integers without using Multiplication. The implementation of int.Parse() also uses multiplication. I have other similar questions where you can manually convert string to int, but that also requires mulitiplying the number by its base 10. This was an interview question I had in one of interviews and I cant seem to find any answer regarding this.
If you assume a base-10 number system and substituting the multiplication by bit shifts (see here) this can be a solution for positive integers.
public int StringToInteger(string value)
{
int number = 0;
foreach (var character in value)
number = (number << 1) + (number << 3) + (character - '0');
return number;
}
See the example on ideone.
The only assumption is that the characters '0' to '9' lie directly next to each other in the character set. The digit-characters are converted to their integer value using character - '0'.
Edit:
For negative integers this version (see here) works.
public static int StringToInteger(string value)
{
bool negative = false;
int i = 0;
if (value[0] == '-')
{
negative = true;
++i;
}
int number = 0;
for (; i < value.Length; ++i)
{
var character = value[i];
number = (number << 1) + (number << 3) + (character - '0');
}
if (negative)
number = -number;
return number;
}
In general you should take errors into account like null checks, problems with other non numeric characters, etc.
It depends. Are we talking about the logical operation of multiplication, or how it's actually done in hardware?
For example, you can convert a hexadecimal (or octal, or any other base two multiplier) string into an integer "without multiplication". You can go character by character and keep oring (|) and bitshifting (<<). This avoids using the * operator.
Doing the same with decimal strings is trickier, but we still have simple addition. You can use loops with addition to do the same thing. Pretty simple to do. Or you can make your own "multiplication table" - hopefully you learned how to multiply numbers in school; you can do the same thing with a computer. And of course, if you're on a decimal computer (rather than binary), you can do the "bitshift", just like with the earlier hexadecimal string. Even with a binary computer, you can use a series of bitshifts - (a << 1) + (a << 3) is the same as a * 2 + a * 8 == a * 10. Careful about negative numbers. You can figure out plenty of tricks to make this interesting.
Of course, both of these are just multiplication in disguise. That's because positional numeric systems are inherently multiplicative. That's how that particular numeric representation works. You can have simplifications that hide this fact (e.g. binary numbers only need 0 and 1, so instead of multiplying, you can have a simple condition
- of course, what you're really doing is still multiplication, just with only two possible inputs and two possible outputs), but it's always there, lurking. << is the same as * 2, even if the hardware that does the operation can be simpler and/or faster.
To do away with multiplication entirely, you need to avoid using a positional system. For example, roman numerals are additive (note that actual roman numerals didn't use the compactification rules we have today - four would be IIII, not IV, and it fourteen could be written in any form like XIIII, IIIIX, IIXII, VVIIII etc.). Converting such a string to integer becomes very easy - just go character by character, and keep adding. If the character is X, add ten. If V, add five. If I, add one. I hope you can see why roman numerals remained popular for so long; positional numeric systems are wonderful when you need to do a lot of multiplication and division. If you're mainly dealing with addition and subtraction, roman numerals work great, and require a lot less schooling (and an abacus is a lot easier to make and use than a positional calculator!).
With assignments like this, there's a lot of hit and miss about what the interviewer actually expects. Maybe they just want to see your thought processes. Do you embrace technicalities (<< is not really multiplication)? Do you know number theory and computer science? Do you just plunge on with your code, or ask for clarification? Do you see it as a fun challenge, or as yet another ridiculous boring interview question that doesn't have any relevance to what your job is? It's impossible for us to tell you the answer the interviewer was looking for.
But I hope I at least gave you a glimpse of possible answers :)
Considering it being an interview question, performance might not be a high priority. Why not just:
private int StringToInt(string value)
{
for (int i = int.MinValue; i <= int.MaxValue; i++)
if (i.ToString() == value)
return i;
return 0; // All code paths must return a value.
}
If the passed string is not an integer, the method will throw an overflow exception.
Any multiplication can be replaced by repeated addition. So you can replace any multiply in an existing algorithm with a version that only uses addition:
static int Multiply(int a, int b)
{
bool isNegative = a > 0 ^ b > 0;
int aPositive = Math.Abs(a);
int bPositive = Math.Abs(b);
int result = 0;
for(int i = 0; i < aPositive; ++i)
{
result += bPositive;
}
if (isNegative) {
result = -result;
}
return result;
}
You could go further and write a specialized String to Int using this idea which minimizes the number of additions (negative number and error handling omitted for brevity):
static int StringToInt(string v)
{
const int BASE = 10;
int result = 0;
int currentBase = 1;
for (int digitIndex = v.Length - 1; digitIndex >= 0; --digitIndex)
{
int digitValue = (int)Char.GetNumericValue(v[digitIndex]);
int accum = 0;
for (int i = 0; i < BASE; ++i)
{
if (i == digitValue)
{
result += accum;
}
accum += currentBase;
}
currentBase = accum;
}
return result;
}
But I don't think that's worth the trouble since performance doesn't seem to be a concern here.

Calculate Greatest Common Divisor (GCD) of more than two values [duplicate]

This question already has answers here:
Greatest Common Divisor from a set of more than 2 integers
(12 answers)
Closed 4 years ago.
In VB.NET or C#, I would like to be able calculate the Greatest Common Divisor (GCD) of one or more values, dynamically, and without using recursive methodology.
I took as a guideline this solution in C# to calculate the GCD of two values. Now, I would like to adapt that solution to be able calculate an undetermined amount of values (one or more values that are contained in a array of values passed to the function below)...
This is what I did by the moment:
VB.NET (original code):
<DebuggerStepperBoundary>
Private Shared Function InternalGetGreatestCommonDivisor(ParamArray values As Integer()) As Integer
' Calculate GCD for 2 or more values...
If (values.Length > 1) Then
Do While Not values.Contains(0)
For Each value As Integer In values
Dim firstMaxValue As Integer = values.Max()
Dim secondMaxValue As Integer = values.OrderByDescending(Function(int As Integer) int)(1)
values(values.ToList.IndexOf(firstMaxValue)) = (firstMaxValue Mod secondMaxValue)
Next value
Loop
Return If(values.Contains(0), values.Max(), values.Min())
Else ' Calculate GCD for a single value...
Return ...
End If
End Function
C# (online code conversion, I didn't tested it at all):
[DebuggerStepperBoundary]
private static int InternalGetGreatestCommonDivisor(params int[] values)
{
// Calculate GCD for 2 or more values...
if (values.Length > 1)
{
while (!values.Contains(0))
{
foreach (int value in values)
{
int firstMaxValue = values.Max();
int secondMaxValue = values.OrderByDescending((int #int) => #int).ElementAtOrDefault(1);
values[values.ToList().IndexOf(firstMaxValue)] = (firstMaxValue % secondMaxValue);
}
}
return (values.Contains(0) ? values.Max() : values.Min());
}
else // Calculate GCD for a single value...
{
return ...;
}
I'm aware that the type conversion to List would affect overall performance for a large amount of values, but the most priority thing is to make this algorithm work as expected, and finally optimize/refactorize it.
My adaptation works as expected for some combinations of values, but it does not work for anothers. For example in this online GCD calculator, if we put these values: {1920, 1080, 5000, 1000, 6800, 5555} in theory the GCD is 5, or at least that is the GCD calculated by that online service, but my algorithm returns 15.
// pass all the values in array and call findGCD function
int findGCD(int arr[], int n)
{
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = getGcd(arr[i], gcd);
}
return gcd;
}
// check for gcd
int getGcd(int x, int y)
{
if (x == 0)
return y;
return gcd(y % x, x);
}
The issue you are facing is caused by the fact that you are leaving the inner loop too early. Checking if any value is 0 is not enough, as you actually have to check if all but one value is 0.
The C# code could look like this:
private static int InternalGetGreatestCommonDivisor(params int[] values)
{
// Calculate GCD for 2 or more values...
if (values.Length > 1)
{
while (values.Count(value => value > 0) != 1)
{
int firstMaxValue = values.Max();
int secondMaxValue = values.OrderByDescending((int #int) => #int).ElementAtOrDefault(1);
values[values.ToList().IndexOf(firstMaxValue)] = (firstMaxValue % secondMaxValue);
}
return values.Max();
}
else
{
// Calculate GCD for a single value...
}
}
The code returns 5 for your example. I'm afraid I can't give you the exact representation for the VB.NET code.
You can do this using Linq:
static int GCD2(int a, int b){
return b == 0 ? Math.Abs(a) : GCD2(b, a % b);
}
static int GCD(int[] numbers){
return numbers.Aggregate(GCD2);
}

Code not returning expected number of even and odds

I have a function that takes in a list of numbers and will return how many even numbers and odd numbers there are in the list. However, I passed in a list of numbers but I'm getting 0 results.
Here is my function -
public static string HowManyEvenAndOdds(List<int> numbers)
{
int numOfOdds = 0;
int numOfEvens = 0;
int numOfBoth = 0;
foreach (int i in numbers) {
bool isEven = i % 2 == 0;
bool isOdd = i % 3 == 0;
numOfBoth = isEven && isOdd ? numOfBoth++ : numOfBoth;
numOfEvens = isEven ? numOfEvens++ : numOfEvens;
numOfOdds = isOdd ? numOfOdds++ : numOfOdds;
}
return string.Format("This list has {0} odd numbers,\n{1} even numbers,\nand {2} numbers that are even and odd.", numOfOdds, numOfEvens, numOfBoth);
}
Any ideas on what I'm doing wrong here? I debugged through it but none of the lists are incrementing.
Thanks
your are not calculating odd in the correct way
i%3 does not catch 5 which is also an odd number, try this instead
bool isEven = i % 2 == 0;
bool isOdd =!isEven;
I agree with Schachaf Gortler's answer as well as p.s.w.g's comment. Just do:
foreach (var number in numbers)
{
// A number is even if, and only if, it's evenly divisible by 2
if (number % 2 == 0)
numEvens++;
// A number is odd if, and only if, it's NOT evenly divisible by 2
// Alternatively, a number is odd if it isn't even and vice versa
else
numOdds++;
}
As p.s.w.g. mentioned, there's no such thing as a number that's both even and odd, so eliminate that completely.
Incidentally, numOfEvens++ retrieves the value and then increments it, which is why your code didn't work.
I think you should have a look at your test for isOdd
Use the Linq Count extension.
int numOfOdds = numbers.Count(x => x % 2 != 0);
int numOfEvens = numbers.Count(x => x % 2 == 0);
Of course you don't need to evaluate both expressions, as per the comment below.

Finding number of digits of a number in C#

I'm trying to write a piece of code in C# to find the number digits of a integer number, the code works perfectly for all numbers (negative and positive) but I have problem with 10, 100,1000 and so on, it shows one less digits than the numbers' actual number of digits. like 1 for 10 and 2 for 100..
long i = 0;
double n;
Console.Write("N? ");
n = Convert.ToInt64(Console.ReadLine());
do
{
n = n / 10;
i++;
}
while(Math.Abs(n) > 1);
Console.WriteLine(i);
Your while condition is Math.Abs(n) > 1, but in the case of 10, you are only greater than 1 the first time. You could change this check to be >=1 and that should fix your problem.
do
{
n = n / 10;
i++;
}
while(Math.Abs(n) >= 1);
Use char.IsDigit:
string input = Console.ReadLine();
int numOfDigits = input.Count(char.IsDigit);
What's wrong with:
Math.Abs(n).ToString(NumberFormatInfo.InvariantInfo).Length;
Indeed, converting a number to a string is computationally expensive compared to some arithmetic, but it is hard to deal with negative nubers, overflow,...
You need to use Math.Abs to make sure the sign is not counted, and it is a safe option to use NumberFormatInfo.InvariantInfo so that for instance certain cultures that use spaces and accents, do not alter the behavior.
public static int NumDigits(int value, double #base)
{
if(#base == 1 || #base <= 0 || value == 0)
{
throw new Exception();
}
double rawlog = Math.Log(Math.Abs(value), #base);
return rawlog - (rawlog % 1);
}
This NumDigits function is designed to find the number of digits for a value in any base. It also includes error handling for invalid input. The # with the base variable is to make it a verbatim variable (because base is a keyword).
Console.ReadLine().Replace(",", String.Empty).Length;
this will count all the char in a string
int amount = 0;
string input = Console.ReadLine();
char[] chars = input.ToArray();
foreach (char c in chars)
{
amount++;
}
Console.WriteLine(amount.ToString());
Console.ReadKey();

C# A loop using while. Variable displayed only once

I have a small problem. My code is this one :
int c = 0;
int i = 0;
int a = 28;
while (i < a) {
i++;
if (i % a == 0) {
c += i;
Console.WriteLine(i.ToString());
}
}
Why does the string i is displayed only once, after the end of the while ? It should be displayed a times.
Your help will be appreciated !
Your if condition is opposite it should be:
if (a % i == 0)
Currently you are trying to do remainder division with i % a and it will only meet the condition when i reaches 28, so you get the output once.
% is for modulus division, which basically divides by the number and gives you back the remainder. When you're loop reaches 28 it divides it by 28 and the resulting remainder is 0. This only happens once "when your loop reaches 28".
It would help if you told us what was printed out. I guess it is 28 because
i % a
returns the reminder of
i / a
(i divided by a) and it is only 0 when i is equal to a, i.e., 28.

Categories