Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My task is to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11. Where the input contains a single line with an integer N, 1≤N≤1000000000.
I have to pass 8 tests, so far I've only passed 4/8. An input could be 13 where the expected is 11.
Sample input
13
Sample output
11
To clarify I do not get the output from the tests, only the results of them.
Any thoughts on how I can update the code?
public class Reversebinary
{
public static void Main()
{
//Convert Decimal to binary
int num;
string binary, reversed;
//Read integer value from console
num = int.Parse(Console.ReadLine());
//Console.WriteLine(num);
if (num > 1 && num < 1000000000)
{
//Convert the integer value to string binary
binary = Convert.ToString(num, 2);
//reverse string binary
reversed = reverseString(binary);
//Console.WriteLine("binary: " + binary);
//Convert reversed string binary to int32 and print out
Console.WriteLine(Convert.ToInt32(reversed, 2));
}
else
Console.WriteLine("Number is not between 1 or 1000000000");
}
static string reverseString(string str)
{
return new string(str.Reverse().ToArray());
}
}
EDIT1: clarification of the tests.
EDIT2: please understand I just want your opinion on the code so I can alter to it to succed the tests. I am not asking for you to provide me code.
EDIT3: Problem solved, I passed the tests after including greater/lesser or equals operator. Thanks for all your inputs.
At least, numbers are in 1≤N≤1000000000 and you are not considering 1 and 1000000000.
if (num >= 1 && num <= 1000000000)
{
//Convert the integer value to string binary
binary = Convert.ToString(num, 2);
//reverse string binary
reversed = reverseString(binary);
//Console.WriteLine("binary: " + binary);
//Convert reversed string binary to int32 and print out
Console.WriteLine(Convert.ToInt32(reversed, 2));
}
Also, you can use int.TryParse instead of int.Parse to avoid exceptions.
So your if condition should look like this
int num = 0;
if (int.TryParse(Console.ReadLine(), out num) && num >= 1 && num <= 1000000000)
{
...
}
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Reversebinary
{
class Reversebinary
{
static byte[] reverseBinary = new byte[] {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
static void Main(string[] args)
{
//Convert Decimal to binary
int num;
int reversed;
//Read integer value from console
num = int.Parse(Console.ReadLine());
if (num >= 0 && num <= 15)
{
//reverse string binary
reversed = reverseBinary[num];
Console.WriteLine(reversed.ToString("x2"));
}
else
Console.WriteLine("Number is not between 0 and 15");
}
}
}
Related
Can anybody help me with the of bit swapping in c#. It actually goes like this that the function accepts a number then it will convert it into binary and then swap its any bits and then convert it into decimal and the return the number.
Here is what I have tried:
DectoBin(int num) {
stringBuilder strBin = new StringBuilder();
while (num / 2 ! =1) {
strBin.Append((num % 2).ToString());
num = num / 2;
}
String str = strBin.ToString();
int BinDec(string str)
int DecNum = 0;
for (int i = str.length - 1; i >= 0; i++) {
DecNum = +DecNum
int.parse(str[k++] * pow(2, i);
}
return DecNum;
}
I need c# code of this problem soon. If anybody can provide me the code, I would be really thankful.
Your question is vague one, however, I can provide some suggestions. First, let's represent the initial int as a convenient string:
int value = ...
// Meanful bits only : 5 -> "101" (without leading zeroes)
string bits = Convert.ToString(unchecked((uint) value), 2);
// All 32 bits : 5 -> "00000000000000000000000000000101"
string allBits = Convert.ToString(unchecked((uint) value), 2).PadLeft(32, '0');
Time to query; let's use Linq whcih can be very convenient. Depending on what does swap mean it can be
using System.Linq;
...
// reversed bits: "101" -> "101", "100" -> "001", etc.
// but either "bits" or "allBits" as an argument
string result = string.Concat(bits.Reverse());
Or
// each '0' truns into "1" and vice versa: "101" -> "010", "100" -> "011" etc
// but either "bits" or "allBits" as an argument
string result = string.Concat(bits.Select(b => b == '1' ? '0' : '1'));
Finally, let's take int back with a help of Convert:
int outcome = unchecked((int)Convert.ToUInt32(result, 2));
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have two integers, say 4 and 11, and I have a string for example Month04
I want to able to compare that string to the range of numbers between 11 and 4.
So in the other ways a loop which has (if Month04.contains(11,10,9,8,7,6,5,4) then
How can I solve that elegantly?
Regards
You can use any() to check if the number exists in the string and Enumerable.Range() to create the numbers list
string month = "Month04";
int num1 = 4;
int num2 = 11;
IEnumerable<int> numbersList = Enumerable.Range(num1, num2 - num1 + 1) ;
if (numbersList.Any(x => month.Contains(x.ToString())))
{
// then
}
I suggest you create a generic method for this:
public static bool CheckNameInRangeOfIntegers(int lowerBound, int upperBound, string inputString)
{
List<int> rangeOfIntegers=Enumerable.Range(lowerBound,(upperBound-lowerBound + 1)).ToList();
return rangeOfIntegers.Any(x=>inputString.Contains(x.ToString()));
}
Example can be called as :
Console.WriteLine(CheckNameInRangeOfIntegers(4,11,"Month4")); // true
Console.WriteLine(CheckNameInRangeOfIntegers(4,11,"Month1")); // false
Please note: Be clear about your scenarios, if you are processing with .Any() followed by a .Contains() then you will be in trouble in some cases, for example, lowerBound = 1, uppeBound=10, and inputString="Month11"
If your all months ends with digits then you can try below,
int startIndex = 4; //I used variables to define starting index and end index
int endIndex = 11;
List<int> numbers = Enumerable.Range(startIndex, (endIndex-startIndex + 1)).ToList();
if (numbers.Any(x => "Month04".EndsWith(x.ToString())))
{
//Your business logic
}
Here's yet another example using the Regex pattern \d+ which will match every digit group in the string (04 in this case). Then we can cast those matches to integers, and finally, Linq expressions Intersect() and .Any() will return true if any matching values exist between the two integer collections.
string s = "Month04";
Regex pattern = new Regex(#"\d+");
var numbersInString = pattern.Matches(s).Cast<Match>().Select(x = int.Parse(x.Value));
int lowerBound = 4;
int upperBound = 11;
var range = Enumerable.Range(lowerBound, upperBound - lowerBound + 1);
if (numbersInString.Intersect(range).Any())
{
//Match
}
This way:
int[] numbers = new int[] { 11, 10, 9, 8, 7, 6, 5, 4 };
string str = "Month04";
int number = int.Parse(str.Replace("Month", ""));
if (numbers.Contains(number))
{
Console.WriteLine("YEEE!");
}
This question already has answers here:
Increment an index that uses numbers and characters (aka Base36 numbers)
(4 answers)
Closed 6 years ago.
Can anyone help with the logic for the below scenario please?
**Input -> Output**
00000 --> 00001
00009 --> 0000A
0000Z --> 00010
..
..
0002Z --> 00030
00039 --> 0003A
Any suggestions please?
EDIT
Thanks all for your suggestions. :) This is what I tried and it works, not sure if could break at some condition though? :/
public static void Main(string[] args)
{
string number = "0001Z";
var result = Increment(number);
}
private static String Increment(String number)
{
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char lastChar = number[number.Length - 1];
string fragment = number.Substring(0, number.Length - 1);
if (chars.IndexOf(lastChar) < 35)
{
lastChar = chars[chars.IndexOf(lastChar) + 1];
string nextNumber = fragment + lastChar;
return nextNumber;
}
return Increment(fragment) + '0';
}
PS: Increment an index that uses numbers and characters (aka Base36 numbers) - this is where I got it from, so may be duplicate question.. sorry.
I have a couple of methods that I made to convert an integer to/from a different base. I'm sure they probably could be improved. But they may get you started. So convert your base 36 "number" to int, increment by 1, then convert back to base 36. This method uses recursion which is probably not necessary. I'd be interested to know if there are any more efficient methods for this.
These method assumes no other characters besides 0-9 and A-Z
void Main()
{
string input = "0000Z";
int value = baseToInt(input, 36);
value++;
string output = intToBase(value, 36).PadLeft(5, '0');
Console.WriteLine("Input: {0}", input);
Console.WriteLine("Output: {0}", output);
}
public string intToBase(int input, int #base)
{
var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (#base < 2 || #base > 36)
{
throw new ArgumentOutOfRangeException("base", "Must specify a base between 2 and 36, inclusive");
}
if (input < #base && input >= 0)
{
return digits[input].ToString();
}
else
{
return intToBase(input / #base, #base) + digits[input % #base].ToString();
}
}
public int baseToInt(string input, int #base)
{
var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (#base < 2 || #base > 36)
{
throw new ArgumentOutOfRangeException("base", "Must specify a base between 2 and 36, inclusive");
}
var digitsInBase = digits.Substring(0, #base);
if (input.Any(c => !digitsInBase.Contains(c)))
{
throw new ArgumentOutOfRangeException("input", string.Format("Input is not a valid base {0} number", #base));
}
return (int)input.Select((c, i) => Math.Pow(#base, input.Length - (i + 1)) * digitsInBase.IndexOf(c)).Sum();
}
Output:
Input: 0000Z
Output: 00010
Alright so I am making a program to verify a 4 digit code.
The computer generates a 4 digit code
The user types in a 4 digit code. Their guess.
the computer tells them how many digits are
guessed correctly in the correct place and how many digits have
been guessed correctly but in the wrong place.
The user gets 12 guesses to either win – guess the right code. Or
lose – run out of guesses.
So basically, my program doesn't seem to actually verify whether the code is correct but i cant see why not because i have if and for loops for verification, please take a look.
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int DigitOne = random.Next(0, 10);
int DigitTwo = random.Next(0, 10);
int DigitThree = random.Next(0, 10);
int DigitFour = random.Next(0, 10);
byte[] code = new byte[4];
code[0] = Convert.ToByte(DigitOne);
code[1] = Convert.ToByte(DigitTwo);
code[2] = Convert.ToByte(DigitThree);
code[3] = Convert.ToByte(DigitFour);
bool CodeCorrect = false;
Console.WriteLine(code[0] +""+ code[1] +""+ code[2]+""+code [3] );
Console.WriteLine("You have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while (AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
for (int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(Console.Read()) - 48;
}
if (UserCode.Length != 4)
{
Console.WriteLine("Error. Try Again.\n");
}
else
{
int UserDigitOne = UserCode[0];
int UserDigitTwo = UserCode[1];
int UserDigitThree = UserCode[2];
int UserDigitFour = UserCode[3];
for (int i = 0; i < 4; i++)
{
if (UserCode[i] == code[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
}
}
if (UserCode[0] == code[0] && UserCode[1] == code[1] && UserCode[2] == code[2] && UserCode[3] == code[3])
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if (AmountOfGuesses > 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
If you step through the code after it generated the number 1246, and then input the same number from the command line, convert it to a char array, then convert each char to a byte, you'll get the following four bytes:
49 50 52 54
These correspond to the ASCII representations of each char, NOT the actual numbers.
Try something like this:
int[] input = new int[4];
for(int i = 0; i < 4; i++ )
{
input[i] = Convert.ToInt32(Console.Read()) - 48;
}
The -48 should turn your ASCII code into the actual numerical representation that was provided. Console.Read() reads individual characters rather than the full line.
Also, you don't have to say:
CodeCorrect == false
This is more simply represented as:
!CodeCorrect
Similarly, if it was set to true, it would just be:
CodeCorrect
I also suggest using a for loop to set multiple elements in an array rather than manually writing out each line of code. It's not a big deal for small arrays, but it's good practice.
UPDATE: Here's a revised version of the full program:
class Program
{
public static Random random = new Random();
static void Main(string[] args)
{
int[] randCombination = new int[4];
for (int i = 0; i < 4; i++)
{
randCombination[i] = random.Next(0, 10);
Console.Write(randCombination[i].ToString());
}
bool CodeCorrect = false;
Console.WriteLine("\nYou have 12 guesses before you will be permenantly locked out.\n");
int AmountOfGuesses = 0;
while(AmountOfGuesses < 12 && !CodeCorrect)
{
Console.WriteLine("Enter 4 digit code to unlock the safe: ");
int[] UserCode = new int[4];
string input = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(input, out n);
int correctCount = 0;
if(input.Length != 4 || !isNumeric)
{
Console.WriteLine("Error. Input code was not a 4 digit number.\n");
}
else
{
for(int i = 0; i < 4; i++)
{
UserCode[i] = Convert.ToInt32(input[i]) - 48;
if(UserCode[i] == randCombination[i])
{
Console.WriteLine("The digit at position " + (i + 1) + " is correct.");
correctCount++;
}
}
if(correctCount == 4)
{
CodeCorrect = true;
Console.WriteLine("Code Correct. Safe unlocked.");
}
}
AmountOfGuesses++;
}
if(AmountOfGuesses >= 12)
{
Console.WriteLine("Code Incorrect. Safe Locked permenantly.");
}
Console.ReadLine();
}
}
A couple of things were changed:
Added a for loop at the top that generates a random number, enters it into an array of ints and then prints it to standard output.
I changed the way user input is read back to the Console.ReadLine(). The reason for this is to check if the user inputted a four digit integer. the int.TryParse statement makes sure the input is an int, and the Length property checks the length.
I also used a counter to count each correct guess. If 4 correct digit guesses were made, the safe is unlocked.
Your final if statement would never have evaluated because Amount of Guesses would equal 12, not be greater than it. Changed it to >= from >. Always be on the lookout for small things like this.
EDIT #2: For more information on int.TryParse, see the following:
http://www.dotnetperls.com/int-tryparse
How the int.TryParse actually works
You are comparing numbers with the character representation of a number. Each value of code[] represents an actual number. You then compare those values with the values in UserCode which is a string, meaning there is a character at each index. It is never the case that ((byte)'4') == ((byte)4) (using 4 as an example, but works for any numerical digit).
One way around this is to parse each user input character into a byte using the byte.Parse method.
For fun learning purposes look at the output from the following code:
for (char i = '0'; i <= '9'; i++)
{
Console.WriteLine("char: " + i + "; value: " + ((byte)i));
}
The output is actually:
char: 0; value: 48
char: 1; value: 49
char: 2; value: 50
char: 3; value: 51
char: 4; value: 52
char: 5; value: 53
char: 6; value: 54
char: 7; value: 55
char: 8; value: 56
char: 9; value: 57
This is due to string encoding.
I would also recommend that one you have your code working that you submit it to the fine folks at the Code Review site to review other aspects of the code which could use work.
I have a series of number as such: [1 2 4 8 16 32 64 128], if I input a number, i.e. 66, then the output should be 64 and 2. If I input 87, then the output should be 64, 16, 4, 2, 1.
(Basically, it first divide by the largest possible number, find the remainder, then keep dividing by the largest number possible, until the remainder is 0. Or another way maybe just to subtract the largest possible number and keep subtracting like that until it reaches 0.)
I'm thinking of a recursive function, but not really sure. Any help?
Thanks.
class Program
{
[Flags]
enum Bits
{
_1 = 1,
_2 = 2,
_4 = 4,
_8 = 8,
_16 = 16,
_32 = 32,
_64 = 64,
_128 = 128
}
static void Main(string[] args)
{
var b = (Bits)87;
Console.WriteLine(b);
Console.ReadKey();
}
}
Here's the iterative version
public static IEnumerable<int> FindIndex(int input)
{
var power = 0;
while (input > 0)
{
var digit = input % 2;
if (digit == 1)
{
yield return (int)Math.Pow(2, power);
}
input /= 2;
power++;
}
}
and here's the recursive version
public static void FindIndexRec(int input, int power, ICollection<int> numbers)
{
if (input == 0)
{
return;
}
var digit = input % 2;
if (digit == 1)
{
numbers.Add((int)Math.Pow(2, power));
}
FindIndexRec(input / 2, ++power, numbers);
}
and you can call it like
var numbers = new List<int>();
FindIndexRec(input, 0, numbers);
You could use bit masks. In fact, scratch that - you should use bit masks! That is almost certainly how the error code was created, and it's how it should be picked apart. Anything else is highly likely to confuse your audience of other programmers.
I make no claims to represent all programmers, nor do I claim to be any good, but I am a programmer, and all the other answers confused me. It's obviously a bitwise "problem", so why obfuscate?
There's no need to even store the result anywhere, since it's as quick to recompute it every time, like so:
for(int i=0;i<8;++i) {
if((error&(1<<i))!=0 {
// 1<<i is in the resulting list.
}
}
List<int> additives = new List<int>()
List<int> sourceNumbers = new List<int> { 1, 2, 4, 8, 16, 32, 64, 128 };
int sourceNumber = 87;
foreach(var number in sourceNumbers.Reverse())
{
if(sourceNumber % number > 0)
{
additives.Add(number);
sourceNumber -= number;
}
else
{
additives.Add(number);
break;
}
}
Here's a pretty naive iterated solution in pseudocode. Try to take it somewhere more interesting from here. You can do it recursively, you can convert the integer to binary representation and iterate on that string, id imagine theres a clever way to do it with LINQ very concisely, etc.
v = inputNumber
while(v > 0):
temp = greatest power of 2 less than v
print temp
v -= temp
PS - this does not explictly store the series in question - it presumes powers of 2.
string calculate(int input)
{
string output = string.Empty;
int[] series = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 };
foreach (int i in series.Reverse<int>())
{
if (input >= i)
{
output += i.ToString() + " ";
input -= i;
}
}
return output;
}
This one will work with input numbers greater than 256:
int[] calculate(int input)
{
List<int> retVal = new List<int>();
string output = string.Empty;
int[] series = new int[] { 1, 2, 4, 8, 16, 32, 64, 128 };
foreach (int i in series.Reverse<int>())
{
while (input >= i)
{
retVal.Add(i);
input -= i;
}
}
return retVal.ToArray();
}
Ex:
var result = calculate(284);
// result = 128, 128, 16, 8, 4
IEnumerable<int> GetFlags(int input,IEnumerable<int> series)
{
foreach (int value in series)
if ((input & value)==value)
yield return value;
}
Or LINQ solution to the problem.
IEnumerable<int> GetFlags(int input, IEnumerable<int> series)
{
return series.Where(x => (x & input) == x);
}
Programming aside, you can also look at it mathematically. It's basically 2 to the power of (integer value of) log(2, input)
Putting this in a recursive function would be easy ofcourse, it would even look simple and smooth, but I doubt it being less computationally complex and it sure doesn't help with your homework, just thought I would throw it here.