C# trying to fill up a binary number to 4 digit blocks - c#

I have a base-n-converter and I wanted it to output all values in 4 digit blocks (1111 -> 1111, 101 -> 0101, 110101 -> 00110101). For this, I made this piece in vscode to try and make it work.
using System;
namespace Test
{
using static intUtilities;
class Program
{
static void Main(string[] args)
{
string number = "";
int[] wholenumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(;;)
{
Console.WriteLine("enter binary number");
number = Console.ReadLine();
Console.WriteLine("is number length divisible by 4? " + Contains(wholenumbers, number.Length/4f));
Console.WriteLine(number.Length/4f);
while(!Contains(wholenumbers, number.Length/4f))
{
number = "0" + number;
}
Console.WriteLine(number);
Console.ReadLine();
}
}
}
public class intUtilities
{
public static bool Contains(int[] array, float number)
{
foreach(int i in array)
{
if(i == number)
{
return true;
}
else {return false;}
}
return false;
}
}
}
For inputting 111, I am expecting an output of 0111, which does happen, but if I input 111111, I am expecting 00111111, but there is no output. When executing the while loop, it should catch the moment when numbers.Length / 4 is "2" (which is when therre would be 8 digits) and break the loop, but for some reason, it doesnt and keeps on adding zeros to the string. It even reads out numbers.Length / 4 as "2" at some point but doesnt break the loop. The code only seems to work for a target size of 4 digits, where numbers.Length / 4 would be "1". Is there a way to correct that? Or even an easier workaround?

There are a number of "interesting" issues with this code, but to answer your immediate question, you need to remove the else {return false;} line. This prevents you from searching over every element in the wholeNumbers array - or more specifically, you only query the first element in the wholeNumbers array (which is the value 1) which is why the code only works correctly for the first 4-bit block of binary digits.
In the spirit of your approach, a possible implementation is:
void Main()
{
string number = "";
Console.WriteLine("enter binary number");
number = Console.ReadLine();
while (number.Length % 4 != 0)
{
number = "0" + number;
}
Console.WriteLine(number);
}

The original question ('why doesn't this work') is answered by Phillip Ngan.
Just fyi the correct result can be gotten in a simple calculation without a loop:
void Main
{
Console.WriteLine("enter binary number");
string number = Console.ReadLine();
int padLength = (4 - (number.Length % 4)) % 4;
number = "000".Substring(0, padLength)+number;
Console.WriteLine(number);
}
edit: Just noticed this is simply a variant for the solution proposed by John Glenn.

Or even an easier workaround?
Relying on the usual "round an integer up to the nearest N" of "integer, divide by N, add one and times by N" we can use this to pad the left of the binary string out to the next "multiple of 4" up from the current length
var x= "01111";
var y = x.PadLeft(((x.Length/4)+1)*4, '0');
y is "00001111";
If you don't like all the parentheses you can use precedence to the same effect
.PadLeft(x.Length/4*4+4, '0');
Hopefully most future readers of the code will remember their high school maths lessons 😀

You can use the modulus function to determine the remainder of one number (the string length) divided by another number (4). The entire effect can be shortened to this:
// find how many characters don't fit into a block of four
int leftovers = numbers.Length % 4;
// determine how many numbers to pad
int padding =
(4 - leftovers) // this is the number of characters we have to add to get an even group of 4
% 4; // this will ensure that if leftovers is 0, then instead of padding 4 characters we don't pad any
// pad the string
string displayMe = numbers.PadLeft(numbers.Length + padding, '0');

Related

Why is the output of my solution to PlusOne (LeetCode Problem) so different from what I expect?

I'm just starting out on LeetCode doing some of the 'easy' problems and I'm trying to solve a problem called 'PlusOne' where you're asked to do the following:
"You are given a large integer represented as an integer array digits, where each digits[i] is the i-th digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits."
Below is the solution I came up with. The input is digits = [1, 2, 3].
static int[] PlusOne(int[] digits)
{
string digitsToString = string.Join(string.Empty, digits);
int stringToInt = Convert.ToInt32(digitsToString);
stringToInt += 1;
string outputString = stringToInt.ToString();
int[] output = outputString.Select(x => Convert.ToInt32(x)).ToArray();
/*
Tried this as well, but just got the same result
char[] outputCharArr = stringToInt.ToString().ToCharArray();
int[] output = Array.ConvertAll(outputCharArr, Convert.ToInt32);
*/
return output;
}
The expected output is [1, 2, 4], but what I get is [49, 50, 52]. I'm completely baffled as to why this the output I'm getting so if someone could explain it to me I'd be extremely appreciative!
Yong's answer will solve the problem you're having with your approach. Your solution will work up until a point but for very large numbers it will fail once you get out of range for a 32 bit integer.
Alternatively you can increment the digits like Yong hinted at, however you need to handle rolling over to "10" back to 0 and incrementing the previous digit, which is possibly one of the goals of the exercise.
public static int[] PlusOne(int[] digits)
{
return incrementPosition(digits, digits.Length-1);
}
private static int[] incrementPosition(int[] digits, int position)
{
if (position < 0 || position > digits.Length)
throw new ArgumentException("Position falls outside of digit length.");
if (digits[position] < 0 || digits[position] > 9)
throw new ArgumentException($"The digit at position {position} was out of range.");
digits[position]++;
if (digits[position] >= 10)
{
digits[position] = 0;
if (position > 0)
digits = incrementPosition(digits, position - 1);
else
{
int[] updatedDigits = new int[digits.Length + 1];
updatedDigits[0] = 1;
digits.CopyTo(updatedDigits, 1);
digits = updatedDigits;
}
}
return digits;
}
This assumes that the array contains single-digit elements /w base-10 incrementing, and represents a positive value. There is a basic check for when a particular digit is incremented. This code handles when a digit rolls over, including when a "full" array (I.e. 9, 9, 9) rolls over, inserting a new digit converting 999 to 1000.
The problem was from here:
string outputString = stringToInt.ToString();
int[] output = outputString.Select(x => Convert.ToInt32(x)).ToArray();
Which you are converting a char to int.
According to here, you will get the result of 49 when casting from a '1' (char) [Known as ASCII].
char
int
'1'
49
'2'
50
'4'
52
If your int array with a guarantee with orders (smallest to largest), you can just update the last value of the array as below:
static int[] PlusOne(int[] digits)
{
digits[digits.Length - 1] += 1;
return digits;
}
Sample .NET Fiddle

pls pls help me understand how Console.WriteLine() work

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Program
{
class Program
{
static void Main(string[] args)
{
int num, reverse = 0;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
while (num != 0)
{
reverse = reverse * 10;
reverse = reverse + num % 10;
num = num / 10;
}
Console.WriteLine("Reverse of Entered Number is : "+reverse);
}
}
}
I can grasp at the concept of the previous values of reverse accumulating during the iterations of the loop but why doesnt WriteLine() also output the string "Reverse of Entered Number is: " 3 times? I know it somewhat happens if I enter it in the loop body but the reverse output is still:
blah blah blah: 3 // I understand this
" " : 32 // I thought this was going to output 2
" " : 321 // while this outputs 1
Why is the "+ reverse" bit the only command executed? and not the whole line?
im sorry if this is a very basic or dumb question, its really bothering me had to create a SO account for it.
Let's walk through the program:
It starts with the variables num and reverse are initialized to 0;
int num, reverse = 0;
Now, a prompt is written to the console and Console.ReadLine() is used to read input from the user, which is parsed as an integer into the variable of num:
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
For this example, let's assume the user entered the value 123.
Now, the application will loop as long as num doesn't get set to 0
while (num != 0)
{
Inside the loop, the value of reverse is multiplied by 10. The first time through, this will still be 0, since 0 * 10 is 0.
reverse = reverse * 10;
This is followed by adding num modulus 10 to reverse. Basically, this will return the last digit of whatever number the user entered. So if the user entered 123, this will be set to 3 the first time through the loop.
reverse = reverse + num % 10;
Now, the user's entered value stored in num is devided by 10. Since it's an int, fractional values are truncated, so 123 becomes 12.
num = num / 10;
We now restart the loop, but with num set to 12 and reverse set to 3.
At the top of the loop, reverse gets multiplied by 10 again, so it's new value is 30.
Then we add the last digit of num, which is 2, making reverse set to 32.
Followed by dropping the last digit of num, making it 1.
Once more, we loop, since num still doesn't equal 0, this time with num set to 1 and reverse set to 32.
At the top of the loop, reverse gets multiplied by 10 again, so it's new value is 320.
Then we add the last digit of num, which is 1, making reverse set to 321.
Followed by dropping the last digit of num, making it 0.
This time, num does equal 0, so the loop ends.
}
Console.WriteLine("Reverse of Entered Number is : "+reverse);
The program completes by printing the string "Reverse of Entered Number is : " followed by the final value of reverse.

How to use the length of an integer variable as the termination condition in a for loop

I have a for loop such as:
for (int indexCount = 2, thirdNumber.ToString().Length!=1000; indexCount++)
I want the loop to terminate when there are 1000 digits in thirdNumber. How can I do this?
It's not possible to have an int with 1000 digits. The maximum int value is 2,147,483,647, which is only 10 digits. As far as I'm aware, there are no built-in data types that would represent a number with 1000 digits, or even 100 digits for that matter.
Edit:
A BigInteger can hold an arbitrarily large number (thanks Bradley Uffner). You'll need to add a reference to the System.Numerics assembly. If you use/are using that as your data type, your original comparison of thirdNumber.ToString()!=1000 would be a valid check to see if it is not 1000 digits.
You could also take a more numbers-based approach and compare the BigInteger being checked to the smallest thousand digit number, which is a 1 followed by 999 zeroes. I'm not sure which method would be faster with numbers of this size, though I'd suspect the comparison between two BigIntegers.
class Program
{
static void Main(string[] args)
{
BigInteger minThousandDigits = BigInteger.Parse(new string('9', 999)) + 1;
BigInteger thousandMoreDigits = BigInteger.Parse(new string('5', 1000));
BigInteger notAThousandDigits = BigInteger.Parse(new string('9', 999));
//Displays false
Console.WriteLine($"Is the first number less than a thousand digits? {thousandMoreDigits < minThousandDigits}");
//Displays true
Console.WriteLine($"Is the second number less than a thousand digits? {notAThousandDigits < minThousandDigits}");
Console.ReadLine();
}
}
Use a do loop:
int indexCount = 2;
do
{
// Whatever
indexCount++;
} while (thirdNumber.ToString().Length != 1000);
Note that the loop will always execute at least once in the above example. You can avoid this by using a break statement:
int indexCount = 2;
do
{
if (thirdNumber.ToString().Length == 1000) break;
// Whatever
indexCount++;
} while (true);
The above assumes that length will eventually be equal to 1000, otherwise you'll have an infinite loop.

How can you separate a string of numbers to single digits using division and the modulo operator?

Lets say someone enter a four digit number 1234 in the console. How can you separate this number in to 1 2 3 4 using only division and the modulo operator?
public static void MathProblem()
{
Console.WriteLine("Type a four digit number:");
//Ex input: 1234
string inputNumber = Console.ReadLine();
// I'm guessing you first need to parse the
// string as an int in some way?
// And then assign it to some variable
// Now, for seperating the digits to be: 1 2 3 4,
// you can (and must) use both division (/), and the remainder (%).
// The first one will be simple, just dividing value with 1000, but
// how about the others? (Remember, % also need to be used at least
// once)
Console.Write("{0},{1},{2},{3}", value/1000, ?, ?, ?;
}
Any guidelines for making this possible for any given four digit input?
Since this seems like a homework problem, I'll simply explain the method in a few steps rather than giving you the code. Having parsed the input as an integer,
A number modulo 10 allows you to obtain its last digit.
Dividing (integer division) the number by 10 removes the last digit.
Repeat while the number is greater than 0.
int num = int.Parse(inputNumber);
Console.Write(string.Format("{0},{1},{2},{3}", (num/1000) % 100, (num/100) % 10, (num/10) % 10, num % 10));
OR
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
Console.Write("{0},{1},{2},{3}", listOfInts[3], listOfInts[2], listOfInts[1], listOfInts[0]);
No need to do this by division or modulo operators. Use LINQ. You can get an integer array using LINQ as below:
string inputNumber= "1234"
var intList = inputNumber.Select(digit => int.Parse(digit.ToString()));
Then, you can simply use it as you want like this:
Console.Write("{0},{1},{2},{3}", intList[0]/1000, intList[1], intList[2], intList[3]);
Or simply the way you wanted it using Division and Modulo Operator:
public int[] ParseIntString(int number)
{
List<int> digits= new List<int>();
while(number> 0)
{
digits.Add(number% 10);
number= number/ 10;
}
digits.Reverse();
return digits.ToArray();
}
I hope this helps you
int[] values;
Seperate(inputNumber, out values);
Console.Write("{0},{1},{2},{3}", values[0] / 1000, values[1], values[2], values[3]);
Console.ReadKey();
}
public static void Seperate(string numbers, out int[] values)
{
values = new int[numbers.Length];
for (int x = 0; x <= numbers.Length - 1; x++)
{
values[x] = int.Parse(numbers[x].ToString());
}
}
I just started a course in coding and had this as homework as well. I did it in excel first because I thought it was easier than running code over and over and it's more a math problem than a coding one.
Say the number is 4352.
The first digit is easy, it's the integer of the number / 1000 = 4.
Then you simply multilpy by 1000 to get 4000. Remove that and you get 352. The integer of that / 100 is 3.
Then you times that by 100 to get 300 and remove that and you get 52, the integer of that / 10 is 5. Multiply that by 10 and remove that and you're left with 2.
Just read that you must use % so I suggest getting the last number as a modular of 10

C# - Separate integers/strings with division and remainder

I have a homework that I just can't figure out how to do. I'm not sure if the teacher wrote it wrong(he is a bad typer) or if there is a way to accomplish the task.
I work in Visual C# 2010 Express - Console Application
My task is to:
Read a four digit integer, such as 5893, from the keyboard and display the digits separated from one another by a tab each. Use both integer division and modulus operator % to pick off each digit. If the user enters 4567, the output looks like:
4567
4 5 6 7
Sure I know how to separate the numbers by using \t as well as reading the input and displaying it to the user. But how am I supposed to 'pick off' each digit with division and the remainder operators? Maybe he means something else, but not sure.
And another question...
How do I make sure that what the user types in is a number and not a letter?
Do I have to use Char.IsLetter, because I couldn't figure out how to use it on a parsed string.
Example:
string number1;
int x;
Console.Write("Please enter a number to calculate: ");
number1 = Console.ReadLine();
x = Int32.Parse(number1);
What method am I supposed to use and where do i put it in? Because now i only get an error and the application shuts down if I try to enter e letter.
The first question is really more about maths than programming. You know what the division and modulus operators do. Think about how you could use them to get the last (least significant) digit. Once you've done that you can apply a similar technique for the 2nd digit (tens) and then the same for hundreds and thousands and so on.
You've already found Char.IsLetter, but there is also Char.IsDigit, which does what you want more directly. You can do this check for one character and what you have is a string of characters. Have a look at a foreach loop.
System.Int32.TryParse() might be a better choice when converting the String.
Yes, your assignment makes sense. Say you have an integer x = 4567. To pick out the digit at position A you would use:
result = (int)((x / (A * 10)) % 10);
The first part of this (x / (A * 10)) "shifts" x to the right. So a value of A = 1 would divide 4567 by 10 which results in 456.7. You then use the modulo operator "%" to pick out the unit part of that number. Finally you convert to an int to remove the fractional part.
Ok, I won't give the whole solution (after all, this is homework ;)).
This code would check if there's four characters in input:
string input;
do
{
input = Console.ReadLine();
if (input.Length != 4)
Console.WriteLine("You have to enter FOUR digits");
} while (input.Length != 4);
This could be one way of checking the digits:
bool isOk = true;
foreach (char c in input.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("You have to enter four DIGITS");
isOk = false;
break;
}
}
This approach doesn't deal with math but you could do that just as well:
int num = int.Parse(input);
int tensOfThousands = num / 10000;
int thousands = (num - tensOfThousands) / 1000;
int lastDigit = num % 10;
//the rest of the digits are up to you ;)
For everybody new to C#, the solution can be simpler.
// Variables
int number = 1234;
int remainder;
string s = "";
while (number > 0) {
remainder = number % 10;
s = remainder + "\n" + s;
number /= 10;
}
Console.Write (s);

Categories

Resources