Returns incorrect output - c#

Description of challenge:
Have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits.
Your program should perform the following routine on the number:
Arrange the digits in descending order and in ascending order (adding
zeroes to fit it to a 4-digit number), and subtract the smaller
number from the bigger number. Then repeat the previous step.
Performing this routine will always cause you to reach a fixed number: 6174.
Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174).
Your program should return the number of times this routine must be performed until 6174 is reached.
For example: if num is 3524 your program should return 3 because of the following steps:
5432 - 2345 = 3087
8730 - 0378 = 8352
8532 - 2358 = 6174
Web-site where I took this challenge Coderbyte
Problem :
All works correctly until returning the result in Foo() I don't know why but it calls this function some times until Count==2
Please help.Sorry please if I made mistakes and my code is really bad because I am schooler(9 Grade) and I have been programming for half a year
using System;
class MainClass
{
public static int Foo(int num,int Counter)
{
int Count = Counter;
int[] arr = new int[4];
arr[0] = num / 1000;
arr[1] = num % 10;
arr[2] = (num / 100) % 10;
arr[3] = (num % 100) / 10;
Array.Sort(arr);
int[] AscArr = new int[4];
arr.CopyTo(AscArr, 0);
Array.Reverse(arr);
int[] DescArr = arr;
int sub = 0;
string AscStr = string.Empty;
string DescStr = string.Empty;
for (int i = 0; i < AscArr.Length; i++)
{
AscStr += AscArr[i];
}
for (int i = 0; i < DescArr.Length; i++)
{
DescStr += DescArr[i];
}
int b = int.Parse(AscStr);
int a = int.Parse(DescStr);
sub = a - b;
if (sub!=6174)
{
Count++;
Foo(sub,Count);
}
if (sub==6174)
{
Count++;
}
return Count;
}
public static int KaprekarsConstant(int num)
{
int[] arr=new int[4];
arr[0] = num / 1000;
arr[1] = num % 10;
arr[2] = (num / 100) % 10;
arr[3] = (num % 100) / 10;
Array.Sort(arr);
int[] AscArr=new int[4];
arr.CopyTo(AscArr,0);
Array.Reverse(arr);
int[] DescArr = arr;
int sub = 0 ;
string AscStr=string.Empty;
string DescStr = string.Empty;
for (int i = 0; i < AscArr.Length; i++)
{
AscStr += AscArr[i];
}
for (int i = 0; i < DescArr.Length; i++)
{
DescStr += DescArr[i];
}
int b = int.Parse(AscStr);
int a = int.Parse(DescStr);
sub = a - b;
int Counter =1;
int Count=0;
if (Count!=6174)
{
Count = Foo(sub, Counter);
}
return Count;
}
static void Main()
{
// keep this function call here
Console.WriteLine(KaprekarsConstant(int.Parse(Console.ReadLine())));
}
}

Your code is too much complex, plus, your way of dividing number to array is giving wrong results.
// this is wrong you can print array, the numbers goes into wrong indexes
arr[0] = num / 1000;
arr[1] = num % 10;
arr[2] = (num / 100) % 10;
arr[3] = (num % 100) / 10;
Use this:
using System;
class MainClass
{
public static int count = 0;
public static void KaprekarsConstant(int num)
{
if (num == 6174) // base case
return;
count++;
string[] Aarr=new string[4];
string[] Darr = new string[4];
string asc = "", dsc = "";
Aarr[3] = (num % 10).ToString();
Darr[3] = (num % 10).ToString();
num /= 10;
Aarr[2] =(num % 10).ToString();
Darr[2] = (num % 10).ToString();
num /= 10;
Aarr[1] = (num % 10).ToString();
Darr[1] = (num % 10).ToString();
num /= 10;
Aarr[0] =(num % 10).ToString();
Darr[0] = (num % 10).ToString();
Array.Sort(Aarr); // ascneding sorted
Array.Sort<string>(Darr, new Comparison<string>( (i1, i2) => i2.CompareTo(i1))); // descending sorted
for(int i = 0; i< 4;i++)
{
asc += Aarr[i];
dsc += Darr[i];
}
KaprekarsConstant(Convert.ToInt32(dsc) -Convert.ToInt32(asc) );
}
static void Main()
{
KaprekarsConstant(int.Parse(Console.ReadLine()));
Console.WriteLine("\nIt took "+count + "times to reach 6174");
}
}

Related

Appending '0' using concat does not seem to work

I have a program that compares two integer value's length with this extension method
public static int NumDigits(this int n)
{
if (n < 0)
{
n = (n == int.MinValue) ? int.MaxValue : -n;
}
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
return n < 1000000000 ? 9 : 10;
}
And it works perfectly. When I print the value of num1.numDigits(), the value returns 4 (it is worth '1111'. And my other integer: num2.numDigits() returns 2 (it is 11). This is great but when I actually compare them:
int[] rawNum2 = Arrays.DigitArr(num2);
if (num1.NumDigits() > num2.NumDigits())
{
int diff = num1.NumDigits() - num2.NumDigits();
for (int i = 1; i < diff; i++)
{
rawNum2.Append(0);
}
reversedNum2 = rawNum2.Reverse();
}
reversedNum2 is still '11' when it should be '0011'.
This is the class I compiled and used.
public static int[] Append(this int[] source, int value)
{
int[] newValue = source;
newValue = newValue.Concat(new[] { value }).ToArray();
return newValue;
}
public static int[] Reverse(this int[] array)
{
int[] arr = array;
for (int i = 0; i < arr.Length / 2; i++)
{
int tmp = arr[i];
arr[i] = arr[arr.Length - i - 1];
arr[arr.Length - i - 1] = tmp;
}
return arr;
}
public static int[] DigitArr(int n)
{
if (n == 0) return new int[1] { 0 };
var digits = new List<int>();
for (; n != 0; n /= 10)
digits.Add(n % 10);
var arr = digits.ToArray();
Array.Reverse(arr);
return arr;
}
Why is this happening?
You are discarding the return value of the Append method.
Change
rawNum2.Append(0);
to
rawNum2 = rawNum2.Append(0);
inside the for loop.
Your loop could be and should be simplified to:
rawNum2 = rawNum2.PadRight(num1.NumDigits(), '0')
To get the reversedNum2 as 0011 change your loop as below.
for (int i = 1; i <= diff; i++)
{
rawNum2=rawNum2.Append(0);
}
I made two changes changed the for loop to use i<=diff instead of i < diff
and assigning the return value from Append() method into the rawNum2.

Can I find the number of digits of a BigInteger in C#?

I am solving this problem, in which they ask for the index of the first Fibonacci number of 1000 digits, and my first idea was something similar to:
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.NoOfDigits < 1000)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
However, as far as I can tell, there is no method for counting the number of digits of a BigInteger. Is this true? One way of circumventing it is to use the .ToString().Length method of a BigInteger, but I'm told that string processing is slow.
A BigInteger also has a .ToByteArray(), and I thought of converting a BigInteger to a byte array and checking the length of that array - but I don't think that this uniquely determines the number of digits in the BigInteger.
For what it's worth, I implemented another way of solving it, which is manually storing the Fibonacci numbers in array, and which stops as soon as the array is full, and I compared this to the .ToString-based method, which is about 2.5 times slower, but the first method takes 0.1 second, which also seems like a long time.
Edit: I've tested the two suggestions in the answers below (the one with BigInteger.Log and the one with MaxLimitMethod). I get the following run times:
Original method: 00:00:00.0961957
StringMethod: 00:00:00.1535350
BigIntegerLogMethod: 00:00:00.0387479
MaxLimitMethod: 00:00:00.0019509
Program
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
Stopwatch clock = new Stopwatch();
clock.Start();
int index1 = Algorithms.IndexOfNDigits(1000);
clock.Stop();
var elapsedTime1 = clock.Elapsed;
Console.WriteLine(index1);
Console.WriteLine("Original method: {0}",elapsedTime1);
Console.ReadKey();
clock.Reset();
clock.Start();
int index2 = Algorithms.StringMethod(1000);
clock.Stop();
var elapsedTime2 = clock.Elapsed;
Console.WriteLine(index2);
Console.WriteLine("StringMethod: {0}", elapsedTime2);
Console.ReadKey();
clock.Reset();
clock.Start();
int index3 = Algorithms.BigIntegerLogMethod(1000);
clock.Stop();
var elapsedTime3 = clock.Elapsed;
Console.WriteLine(index3);
Console.WriteLine("BigIntegerLogMethod: {0}", elapsedTime3);
Console.ReadKey();
clock.Reset();
clock.Start();
int index4 = Algorithms.MaxLimitMethod(1000);
clock.Stop();
var elapsedTime4 = clock.Elapsed;
Console.WriteLine(index4);
Console.WriteLine("MaxLimitMethod: {0}", elapsedTime4);
Console.ReadKey();
}
}
static class Algorithms
{
//Find the index of the first Fibonacci number of n digits
public static int IndexOfNDigits(int n)
{
if (n == 1) return 1;
int[] firstNumber = new int[n];
int[] secondNumber = new int[n];
firstNumber[0] = 1;
secondNumber[0] = 1;
int currentIndex = 2;
while (firstNumber[n-1] == 0)
{
int carry = 0, singleSum = 0;
int[] tmp = new int[n]; //Placeholder for the sum
for (int i = 0; i<n; i++)
{
singleSum = firstNumber[i] + secondNumber[i];
if (singleSum >= 10) carry = 1;
else carry = 0;
tmp[i] += singleSum % 10;
if (tmp[i] >= 10)
{
tmp[i] = 0;
carry = 1;
}
int countCarries = 0;
while (carry == 1)
{
countCarries++;
if (tmp[i + countCarries] == 9)
{
tmp[i + countCarries] = 0;
tmp[i + countCarries + 1] += 1;
carry = 1;
}
else
{
tmp[i + countCarries] += 1;
carry = 0;
}
}
}
for (int i = 0; i < n; i++ )
{
secondNumber[i] = firstNumber[i];
firstNumber[i] = tmp[i];
}
currentIndex++;
}
return currentIndex;
}
public static int StringMethod(int n)
{
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.ToString().Length < n)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
public static int BigIntegerLogMethod(int n)
{
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (Math.Floor(BigInteger.Log10(x) + 1) < n)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
public static int MaxLimitMethod(int n)
{
BigInteger maxLimit = BigInteger.Pow(10, n - 1);
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.CompareTo(maxLimit) < 0)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
}
Provided that x > 0
int digits = (int)Math.Floor(BigInteger.Log10(x) + 1);
will get the number of digits.
Out of curiosity, I tested the
int digits = x.ToString().Length;
approach. For 100 000 000 iterations, it's 3 times slower than the Log10 solution.
Expanding on my comment--instead of testing based on number of digits, test based on exceeding a constant that has the upper limit of the problem:
public static int MaxLimitMethod(int n)
{
BigInteger maxLimit = BigInteger.Pow(10, n);
BigInteger x = 1;
BigInteger y = 1;
BigInteger tmp = 0;
int currentIndex = 2;
while (x.CompareTo(maxLimit) < 0)
{
tmp = x + y;
y = x;
x = tmp;
currentIndex++;
}
return currentIndex;
}
This should result in a significant performance increase.
UPDATE:
This is an even quicker method on .NET 5 (since GetBitLength() is required):
private static readonly double exponentConvert = Math.Log10(2);
private static readonly BigInteger _ten = 10;
public static int CountDigits(BigInteger value)
{
if (value.IsZero)
return 1;
value = BigInteger.Abs(value);
if (value.IsOne)
return 1;
long numBits = value.GetBitLength();
int base10Digits = (int)(numBits * exponentConvert).Dump();
var reference = BigInteger.Pow(_ten, base10Digits);
if (value >= reference)
base10Digits++;
return base10Digits;
}
The slowest part of this algorithm for large values is the BigInteger.Pow() operation. I have optimized the CountDigits() method in Singulink.Numerics.BigIntegerExtensions with a cache that holds powers of 10, so check that out if you are interested in the fastest possible implementation. It caches powers up to exponents of 1023 by default but if you want to trade memory usage for faster performance on even larger values you can increase the max cached exponent by calling BigIntegerPowCache.GetCache(10, maxSize) where maxSize = maxExponent + 1.
On an i7-3770 CPU, this library takes 350ms to get the digit count for 10 million BigInteger values (single-threaded) when the digit count <= the max cached exponent.
ORIGINAL ANSWER:
The accepted answer is unreliable, as indicated in the comments. This method works for all numbers:
private static int CountDigits(BigInteger value)
{
if (value.IsZero)
return 1;
value = BigInteger.Abs(value);
if (value.IsOne)
return 1;
int exp = (int)Math.Ceiling(BigInteger.Log10(value));
var test = BigInteger.Pow(10, exp);
return value >= test ? exp + 1 : exp;
}

Number of zeroes at the end of factorial

I need to find the number of zeroes at the end of a factorial number. So here is my code, but it doesn't quite work :/
using System;
class Sum
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
long factoriel = 1;
for (int i = 1; i <= n; i++)
{
factoriel *= i;
}
Console.WriteLine(factoriel);
int timesZero = 0;
while(factoriel % 10 != 0)
{
timesZero++;
}
Console.WriteLine(timesZero);
}
}
I know I can use a for loop and divide by 5, but I don't want to. Where is the problem in my code and why isn't it working?
There's problem with your algorithm: integer overflow. Imagine, that you are given
n = 1000
and so n! = 4.0238...e2567; you should not compute n! but count its terms that are in form of (5**p)*m where p and m are some integers:
5 * m gives you one zero
25 * m gives you two zeros
625 * m gives you three zeros etc
The simplest code (which is slow on big n) is
static void Main(string[] args) {
...
int timesZero = 0;
for (int i = 5; i <= n; i += 5) {
int term = i;
while ((term % 5) == 0) {
timesZero += 1;
term /= 5;
}
}
...
}
Much faster implementation is
static void Main(string[] args) {
...
int timesZero = 0;
for (int power5 = 5; power5 <= n; power5 *= 5)
timesZero += n / power5;
...
}
Counting Trailing zeros in Factorial
static int countZerosInFactOf(int n)##
{
int result = 0;
int start = 1;
while (n >= start)
{
start *= 5;
result += (int)n/start;
}
return result;
}
Make sure to add inbuilt Reference System.Numeric
using System.Text;
using System.Threading.Tasks;
using System.Numeric
namespace TrailingZeroFromFact
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a no");
int no = int.Parse(Console.ReadLine());
BigInterger fact = 1;
if (no > 0)
{
for (int i = 1; i <= no; i++)
{
fact = fact * i;
}
Console.WriteLine("{0}!={1}", no, fact);
string str = fact.ToString();
string[] ss = str.Split('0');
int count = 0;
for (int i = ss.Length - 1; i >= 0; i--)
{
if (ss[i] == "")
count = count + 1;
else
break;
}
Console.WriteLine("No of trailing zeroes are = {0}", count);
}
else
{
Console.WriteLine("Can't calculate factorial of negative no");
}
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter the number:");
int n = int.Parse(Console.ReadLine());
int zero = 0;
long fac=1;
for (int i = 1; i <= n; i++)
{
fac *= i;
}
Console.WriteLine("Factorial is:" + fac);
ab:
if (fac % 10 == 0)
{
fac = fac / 10;
zero++;
goto ab;
}
else
{
Console.WriteLine("Zeros are:" + zero);
}
Console.ReadLine();
}
Your code seems fine, just a little correction in the while-condition:
public static int CalculateTrailingZeroes(BigInteger bigNum)
{
int zeroesCounter = 0;
while (bigNum % 10 == 0)
{
zeroesCounter++;
bigNum /=10;
}
return zeroesCounter;
}
That works, I just tested it.

Split number into equal sized groups

Using this example:
var amount = x;
var maxPerGroup = y;
var amountGroups = Ceiling(amount/maxPerGroup);
Can someone help me how to split the Amount into AmountGroups with a max amount per group of maxAmount?
These groups have to be almost the same size.
For example:
amount = 45;
maxPerGroup = 15;
amountGroups = 3;
Result: 15 15 15
I am using C# as language.
Thanks in advance!
number of groups := ceiling(total / max group size)
number per group := floor(total / number of groups)
rem = total % number per group
You will have rem groups with number per group + 1 and number of groups - rem groups with number per group.
EDIT: Example:
total := 50
max group size := 15
number of groups := ceiling(50 / 15) // 4
number per group := floor(50 / 4) // 12
rem := 50 % 12 // 2
2 groups with 13 and 2 with 12.
There are many ways of splitting the amount between groups. It all depends on whether the only factor is the number of groups or if there are any other factors. See:
static void Main(string[] args)
{
List<int> list1 = Split1(48, 15); // result is: 15, 15, 15, 3
List<int> list2 = Split2(48, 15); // result is 12, 12, 12, 12
}
public static List<int> Split1 (int amount, int maxPerGroup)
{
int amountGroups = amount / maxPerGroup;
if (amountGroups * maxPerGroup < amount)
{
amountGroups++;
}
List<int> result = new List<int>();
for (int i = 0; i < amountGroups; i++)
{
result.Add(Math.Min(maxPerGroup, amount));
amount -= Math.Min(maxPerGroup, amount);
}
return result;
}
public static List<int> Split2 (int amount, int maxPerGroup)
{
int amountGroups = amount / maxPerGroup;
if (amountGroups * maxPerGroup < amount)
{
amountGroups++;
}
int groupsLeft = amountGroups;
List<int> result = new List<int>();
while (amount > 0)
{
int nextGroupValue = amount / groupsLeft;
if (nextGroupValue * groupsLeft < amount)
{
nextGroupValue++;
}
result.Add(nextGroupValue);
groupsLeft--;
amount -= nextGroupValue;
}
return result;
}
NOTE
not exact c# just to give you the idea.
I think you are looking for a way to grammatically divide a number in different groups. Without knowing how big the groups are and a random amount of groups.
so let's say x = 30 y = 15. 30/15 = 3 groups of 15 and let's say x= 43 so the number should be like ? 14 14 15
groups (since you already have this calculated correctly)(should be a double)
// maxPerGroup = y
membersPerGroup = floor(amount/groups)
List a = new List
//Is the leftover value of the modulus
leftover = amount%groups;
//Loops for each group
for(int i=0;i<groups;i++){
//If there is a left over value
if(leftover>0){
a.Add(membersPerGroup +1);
leftover--;
}else{
a.Add(membersPerGroup );
}
}
I could write in proper c# but It seems that you found the proper code for it
simple non-optimized solution:
int i = amount;
int j = 0;
int [] groups = new int[amountGroups];
while(i > 0) {
groups[j] += 1;
i--;
j = (j+1)%amountGroups;
}
private static int[] DistributeIntoGroups(int sum, int groupsCount)
{
var baseCount = sum / groupsCount;
var leftover = sum % groupsCount;
var groups = new int[groupsCount];
for (var i = 0; i < groupsCount; i++)
{
groups[i] = baseCount;
if (leftover > 0)
{
groups[i]++;
leftover--;
}
}
return groups;
}
// For separating a collection into ranges
static List<List<T>> Split<T>(List<T> source, int size)
{
// TODO: Prepopulate with the right capacity
List<List<T>> ret = new List<List<T>>();
for (int i = 0; i < source.Count; i += size)
{
ret.Add(source.GetRange(i, Math.Min(size, source.Count - i)));
}
return ret;
}
// For separating an int into a Tuple range
static List<Tuple<int, int>> Split(int source, int size)
{
var ret = new List<Tuple<int, int>>();
for (int i = 0; i < source; i += size)
{
ret.Add(new Tuple<int, int>(i, (i + Math.Min(size, source - i))));
}
return ret;
}
Divide an integer into groups
public class Program
{
static void Main(string[] args)
{
List<int> results = DistributeInteger(20, 3).ToList();//output: 7,7,6
foreach (var result in results)
{
Console.WriteLine(result);
}
Console.Read();
}
public static IEnumerable<int> DistributeInteger(int total, int divider)
{
if (divider == 0)
yield return 0;
int rest = total % divider;
double result = total / (double)divider;
for (int i = 0; i < divider; i++)
{
if (rest-- > 0)
yield return (int)Math.Ceiling(result);
else
yield return (int)Math.Floor(result);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
// I wanted to get count from a datagridview (x)
// and then split into groups based on the
// count from a combobox (n). In my example my
// grid had 1771 rows and was split into: 25 groups
// (4x of 70 and 21x of 71)
// Driver code
int x = myDataGridView.Rows.Count; //1771
int n = assemblies_cmbbox.Items.Count; //25
split(x, n);
//split(amount, maxPerGroup);
}
// Function that prints
// the required sequence
private void split(int x, int n)
{
// If we cannot split the
// number into exactly 'N' parts
if (x < n)
Debug.WriteLine("-1 ");
// If x % n == 0 then the minimum
// difference is 0 and all
// numbers are x / n
else if (x % n == 0)
{
for (int i = 0; i < n; i++)
Debug.WriteLine((x / n) + " ");
}
else
{
// upto n-(x % n) the values
// will be x / n
// after that the values
// will be x / n + 1
int zp = n - (x % n);
int pp = x / n;
for (int i = 0; i < n; i++)
{
if (i >= zp)
Debug.WriteLine((pp + 1) + " ");
else
Debug.WriteLine(pp + " ");
}
}
}
All credits to Sachin.
Visit https://www.geeksforgeeks.org/split-the-number-into-n-parts-such-that-difference-between-the-smallest-and-the-largest-part-is-minimum/
int amount = x;
int maxPerGroup = y;
int amountGroups = new int[Ceiling(amount/maxPerGroup)];
for(int i=0; i<maxPerGroup; i++)
{
if(x>maxPerGroup)
{
amountGroups[i]= maxPerGroup;
x = x-maxPerGroup;
}
else
{
amountGroups[i] = x;
x =0;
}
}

Convert integer to binary in C#

How to convert an integer number into its binary representation?
I'm using this code:
String input = "8";
String output = Convert.ToInt32(input, 2).ToString();
But it throws an exception:
Could not find any parsable digits
Your example has an integer expressed as a string. Let's say your integer was actually an integer, and you want to take the integer and convert it to a binary string.
int value = 8;
string binary = Convert.ToString(value, 2);
Which returns 1000.
Convert from any classic base to any base in C#
string number = "100";
int fromBase = 16;
int toBase = 10;
string result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
// result == "256"
Supported bases are 2, 8, 10 and 16
Very Simple with no extra code, just input, conversion and output.
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html
public string DecimalToBinary(string data)
{
string result = string.Empty;
int rem = 0;
try
{
if (!IsNumeric(data))
error = "Invalid Value - This is not a numeric value";
else
{
int num = int.Parse(data);
while (num > 0)
{
rem = num % 2;
num = num / 2;
result = rem.ToString() + result;
}
}
}
catch (Exception ex)
{
error = ex.Message;
}
return result;
}
primitive way:
public string ToBinary(int n)
{
if (n < 2) return n.ToString();
var divisor = n / 2;
var remainder = n % 2;
return ToBinary(divisor) + remainder;
}
Another alternative but also inline solution using Enumerable and LINQ is:
int number = 25;
string binary = Enumerable.Range(0, (int)Math.Log(number, 2) + 1).Aggregate(string.Empty, (collected, bitshifts) => ((number >> bitshifts) & 1 ) + collected);
Convert.ToInt32(string, base) does not do base conversion into your base. It assumes that the string contains a valid number in the indicated base, and converts to base 10.
So you're getting an error because "8" is not a valid digit in base 2.
String str = "1111";
String Ans = Convert.ToInt32(str, 2).ToString();
Will show 15 (1111 base 2 = 15 base 10)
String str = "f000";
String Ans = Convert.ToInt32(str, 16).ToString();
Will show 61440.
static void convertToBinary(int n)
{
Stack<int> stack = new Stack<int>();
stack.Push(n);
// step 1 : Push the element on the stack
while (n > 1)
{
n = n / 2;
stack.Push(n);
}
// step 2 : Pop the element and print the value
foreach(var val in stack)
{
Console.Write(val % 2);
}
}
I know this answer would look similar to most of the answers already here, but I noticed just about none of them uses a for-loop. This code works, and can be considered simple, in the sense it will work without any special functions, like a ToString() with parameters, and is not too long as well. Maybe some prefer for-loops instead of just while-loop, this may be suitable for them.
public static string ByteConvert (int num)
{
int[] p = new int[8];
string pa = "";
for (int ii = 0; ii<= 7;ii = ii +1)
{
p[7-ii] = num%2;
num = num/2;
}
for (int ii = 0;ii <= 7; ii = ii + 1)
{
pa += p[ii].ToString();
}
return pa;
}
using System;
class Program
{
static void Main(string[] args) {
try {
int i = (int) Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n", i, ToBinary(i));
} catch(Exception e) {
Console.WriteLine("\n{0}\n", e.Message);
}
}
public static string ToBinary(Int64 Decimal) {
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0) {
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}
This function will convert integer to binary in C#:
public static string ToBinary(int N)
{
int d = N;
int q = -1;
int r = -1;
string binNumber = string.Empty;
while (q != 1)
{
r = d % 2;
q = d / 2;
d = q;
binNumber = r.ToString() + binNumber;
}
binNumber = q.ToString() + binNumber;
return binNumber;
}
class Program
{
static void Main(string[] args)
{
var #decimal = 42;
var binaryVal = ToBinary(#decimal, 2);
var binary = "101010";
var decimalVal = ToDecimal(binary, 2);
Console.WriteLine("Binary value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 6;
binaryVal = ToBinary(#decimal, 3);
binary = "20";
decimalVal = ToDecimal(binary, 3);
Console.WriteLine("Base3 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 47;
binaryVal = ToBinary(#decimal, 4);
binary = "233";
decimalVal = ToDecimal(binary, 4);
Console.WriteLine("Base4 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
#decimal = 99;
binaryVal = ToBinary(#decimal, 5);
binary = "344";
decimalVal = ToDecimal(binary, 5);
Console.WriteLine("Base5 value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
Console.WriteLine();
#decimal = 16;
binaryVal = ToBinary(#decimal, 11);
binary = "b";
decimalVal = ToDecimal(binary, 11);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.WriteLine();
Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
Console.WriteLine();
#decimal = 11;
binaryVal = Convert.ToString(#decimal, 16);
binary = "b";
decimalVal = Convert.ToInt32(binary, 16);
Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", #decimal, binaryVal);
Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
Console.ReadLine();
}
static string ToBinary(decimal number, int #base)
{
var round = 0;
var reverseBinary = string.Empty;
while (number > 0)
{
var remainder = number % #base;
reverseBinary += remainder;
round = (int)(number / #base);
number = round;
}
var binaryArray = reverseBinary.ToCharArray();
Array.Reverse(binaryArray);
var binary = new string(binaryArray);
return binary;
}
static double ToDecimal(string binary, int #base)
{
var val = 0d;
if (!binary.All(char.IsNumber))
return 0d;
for (int i = 0; i < binary.Length; i++)
{
var #char = Convert.ToDouble(binary[i].ToString());
var pow = (binary.Length - 1) - i;
val += Math.Pow(#base, pow) * #char;
}
return val;
}
}
Learning sources:
Everything you need to know about binary
including algorithm to convert decimal to binary
class Program{
static void Main(string[] args){
try{
int i = (int)Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
}catch(Exception e){
Console.WriteLine("\n{0}\n",e.Message);
}
}//end Main
public static string ToBinary(Int64 Decimal)
{
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
// The algoritm gives us the binary number in reverse order (mirrored)
// We store it in an array so that we can reverse it back to normal
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}//end class Program
BCL provided Convert.ToString(n, 2) is good, but in case you need an alternate implementation which is few ticks faster than BCL provided one.
Following custom implementation works for all integers(-ve and +ve).
Original source taken from https://davidsekar.com/algorithms/csharp-program-to-convert-decimal-to-binary
static string ToBinary(int n)
{
int j = 0;
char[] output = new char[32];
if (n == 0)
output[j++] = '0';
else
{
int checkBit = 1 << 30;
bool skipInitialZeros = true;
// Check the sign bit separately, as 1<<31 will cause
// +ve integer overflow
if ((n & int.MinValue) == int.MinValue)
{
output[j++] = '1';
skipInitialZeros = false;
}
for (int i = 0; i < 31; i++, checkBit >>= 1)
{
if ((n & checkBit) == 0)
{
if (skipInitialZeros)
continue;
else
output[j++] = '0';
}
else
{
skipInitialZeros = false;
output[j++] = '1';
}
}
}
return new string(output, 0, j);
}
Above code is my implementation. So, I'm eager to hear any feedback :)
// I use this function
public static string ToBinary(long number)
{
string digit = Convert.ToString(number % 2);
if (number >= 2)
{
long remaining = number / 2;
string remainingString = ToBinary(remaining);
return remainingString + digit;
}
return digit;
}
static void Main(string[] args)
{
Console.WriteLine("Enter number for converting to binary numerical system!");
int num = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[16];
//for positive integers
if (num > 0)
{
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
Console.Write(arr[y]);
}
Console.ReadLine();
}
//for negative integers
else if (num < 0)
{
num = (num + 1) * -1;
for (int i = 0; i < 16; i++)
{
if (num > 0)
{
if ((num % 2) == 0)
{
num = num / 2;
arr[16 - (i + 1)] = 0;
}
else if ((num % 2) != 0)
{
num = num / 2;
arr[16 - (i + 1)] = 1;
}
}
}
for (int y = 0; y < 16; y++)
{
if (arr[y] != 0)
{
arr[y] = 0;
}
else
{
arr[y] = 1;
}
Console.Write(arr[y]);
}
Console.ReadLine();
}
}
This might be helpful if you want a concise function that you can call from your main method, inside your class. You may still need to call int.Parse(toBinary(someint)) if you require a number instead of a string but I find this method work pretty well. Additionally, this can be adjusted to use a for loop instead of a do-while if you'd prefer.
public static string toBinary(int base10)
{
string binary = "";
do {
binary = (base10 % 2) + binary;
base10 /= 2;
}
while (base10 > 0);
return binary;
}
toBinary(10) returns the string "1010".
I came across this problem in a coding challenge where you have to convert 32 digit decimal to binary and find the possible combination of the substring.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Numerics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
int numberofinputs = int.Parse(Console.ReadLine());
List<BigInteger> inputdecimal = new List<BigInteger>();
List<string> outputBinary = new List<string>();
for (int i = 0; i < numberofinputs; i++)
{
inputdecimal.Add(BigInteger.Parse(Console.ReadLine(), CultureInfo.InvariantCulture));
}
//processing begins
foreach (var n in inputdecimal)
{
string binary = (binaryconveter(n));
subString(binary, binary.Length);
}
foreach (var item in outputBinary)
{
Console.WriteLine(item);
}
string binaryconveter(BigInteger n)
{
int i;
StringBuilder output = new StringBuilder();
for (i = 0; n > 0; i++)
{
output = output.Append(n % 2);
n = n / 2;
}
return output.ToString();
}
void subString(string str, int n)
{
int zeroodds = 0;
int oneodds = 0;
for (int len = 1; len <= n; len++)
{
for (int i = 0; i <= n - len; i++)
{
int j = i + len - 1;
string substring = "";
for (int k = i; k <= j; k++)
{
substring = String.Concat(substring, str[k]);
}
var resultofstringanalysis = stringanalysis(substring);
if (resultofstringanalysis.Equals("both are odd"))
{
++zeroodds;
++oneodds;
}
else if (resultofstringanalysis.Equals("zeroes are odd"))
{
++zeroodds;
}
else if (resultofstringanalysis.Equals("ones are odd"))
{
++oneodds;
}
}
}
string outputtest = String.Concat(zeroodds.ToString(), ' ', oneodds.ToString());
outputBinary.Add(outputtest);
}
string stringanalysis(string str)
{
int n = str.Length;
int nofZeros = 0;
int nofOnes = 0;
for (int i = 0; i < n; i++)
{
if (str[i] == '0')
{
++nofZeros;
}
if (str[i] == '1')
{
++nofOnes;
}
}
if ((nofZeros != 0 && nofZeros % 2 != 0) && (nofOnes != 0 && nofOnes % 2 != 0))
{
return "both are odd";
}
else if (nofZeros != 0 && nofZeros % 2 != 0)
{
return "zeroes are odd";
}
else if (nofOnes != 0 && nofOnes % 2 != 0)
{
return "ones are odd";
}
else
{
return "nothing";
}
}
Console.ReadKey();
}
}
}
int x=550;
string s=" ";
string y=" ";
while (x>0)
{
s += x%2;
x=x/2;
}
Console.WriteLine(Reverse(s));
}
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
This was a interesting read i was looking for a quick copy paste.
I knew i had done this before long ago with bitmath differently.
Here was my take on it.
// i had this as a extension method in a static class (this int inValue);
public static string ToBinaryString(int inValue)
{
string result = "";
for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
return result;
}
You could stick spacing in there with a bit of modulos in the loop.
// little bit of spacing
if (((bitIndexToTest + 1) % spaceEvery) == 0)
result += ' ';
You could probably use or pass in a stringbuilder and append or index directly to avoid deallocations and also get around the use of += this way;
var b = Convert.ToString(i,2).PadLeft(32,'0').ToCharArray().Reverse().ToArray();
Just one line for 8 bit
Console.WriteLine(Convert.ToString(n, 2).PadLeft(8, '0'));
where n is the number

Categories

Resources