Hot answers tagged

54

First up, your code has bugs. What if one of the numbers is 0? 0 should be positive, but your code treats it as negative in some tests, and positive in others. When comparing against 0 you should use >=, not just >. The actual code is quite readable, though, and the performance is probably not horrible. I would recommend a single return statement ...


54

Why not compare the Booleans themselves? return ((num1 < 0) == (num2 < 0)); This treats zero as "positive". For a stricter interpretation that considers zero to be neither positive nor negative, consider: return (((num1 == 0) == (num2 == 0)) && ((num1 < 0) == (num2 < 0))); (Edit hat tips @MichaelS, @holroy)


43

Yes, there is a more elegant way to do this by adding accessibility modifier to the method use PascalCase casing for naming the method naming the method HasSameSign using the Math.Sign() method private static bool HasSameSign(int num1, int num2) { return Math.Sign(num1) == Math.Sign(num2); }


40

It's not possible to avoid undefined behaviour by testing for it after the fact! If the addition overflows then there is already undefined behaviour here: sum = a + b; so attempting to test afterwards is too late. You have to test for possible overflow before you do a signed addition. (If you're puzzled by this, read Dietz et al. (2012), "Understanding ...


37

You have several different options for this: Guava Google's Guava Library introduces the idea of a Multiset which is capable of counting the occurrences, and also provides a couple of other features. Java 8 If you are using Java 8 (which I highly recommend if you have the ability to do so), your tokenFound method can simply be this: occurrences.merge(...


33

There's actually a bit hack for this : private static boolean isPowerOfTwo(int number) { return number > 0 && ((number & (number - 1)) == 0); } (ref : Bit Twiddling hacks) This exploits the fact, that in binary notation a power of two is a 1 followed by a number of 0's, and the number just below is all 1's equal to that number of 0's :...


27

Yes, there is a better way: int CountOnesFromInteger(unsigned int value) { int count; for (count = 0; value != 0; count++, value &= value-1); return count; } The code relies on the fact that the expression x &= x-1; removes the rightmost bit from x that is set. We keep doing so until no more 1's are removed. This technique is described ...


25

Let's take one function at a time, until we're all done. sepInt sepInt n = if n >= 10 then ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[]) else n `mod` 10 : [] First things first: you'll definitely want to learn a bit about precedence! Normally I'm in favor of adding some unnecessary parentheses if it helps disambiguate a ...


25

Avoid mysterious bit-shifting return ~output + 1; Is the same as: return - (output + 1) + 1; And as: return - output; But the last one is way more obvious than the first one. Do not hide variable declarations int ASCIICodes[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; _Bool negative = 0; If I look at the ...


25

try-with-resources Since Java 7, you should use try-with-resources on your Scanner for safe and efficient handling of the underlying I/O resource: public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { int number = scanner.nextInt(); // other operations } } Mathematical approach You may want to ...


23

There's an easier way. We have the num2words module which can be easily installed via pip: pip install num2words The advantage of this module is that it supports multiple languages: en (English, default) fr (French) de (German) es (Spanish) lt (Lithuanian) lv (Latvian) en_GB (British English) en_IN (Indian English) no (Norwegian) ...


21

You make assumptions which may not be true. Why do you believe that int tmp = a; a = b; b = tmp; actually is compiled down to using an actual variable? It is likely just a register used on the CPU. Have you inspected it? Further, why do you assume that: a ^= b ^= a ^= b; uses fewer registers than a swap? Really, what ...


20

I haven't found any input which isn't handled well by your code. Here are some tests: assertTrue(CanAdd(0, Integer.MAX_VALUE)); assertTrue(CanAdd(0, Integer.MIN_VALUE)); assertTrue(CanAdd(Integer.MIN_VALUE, 0)); assertTrue(CanAdd(-1, Integer.MAX_VALUE)); assertFalse(CanAdd(1, Integer.MAX_VALUE)); assertFalse(CanAdd(-1, Integer.MIN_VALUE)); So, it works but ...


20

Your method is lying. Not only it's displaying the digits, performing every Console.Write operation that needs to happen, it's also performing the "digit-splitting" logic. It's more work than what its name says. For a simple coding exercise it's without consequences, but in larger projects if this is a coding habit you have, it can mean much bigger problems....


19

In the cctype header, you have the std::isdigit(int) function. You can use this instead of your conditions that check if the character is between '0' and '9'. You index into a std::string with an int inside the for loop. Use std::string::size_type as that is the proper type that can index into a std::string (int might be too small). Mark the function as ...


17

First off, Jean-François is absolutely right: you cannot assume any particular bit widths for the built-in types, short, int, long, etc. Use the types defined in stdint.h that have explicit bit widths to ensure that the code is correct and portable. Otherwise, your code looks pretty good, and this is a reasonable implementation. But… Is this a ...


16

You could use explicit layout of the structure to omit values calculation. It can act similar to the union in C/C++: [StructLayout(LayoutKind.Explicit)] public struct CombinedKey : IEquatable<CombinedKey> { [FieldOffset(0)] private readonly long value; [FieldOffset(0)] public readonly int Item1; [FieldOffset(sizeof(int))] ...


16

The other reviews have hit most of the important points, so I'll just provide a single line alternative that uses the C++11 std::regex_match. That function looks like this: bool wasInteger(const std::string &num) { return std::regex_match(num, std::regex("[+-]?[0-9]+")); } With a regex this simple, I might not bother with a wrapper function. ...


15

The good part is that without any real modifications, I can compile your code with lots of the extra compiler flags to detect errors: -Wall, -Wextra, -Werror, -pedantic under -std=c99. That's a good start. There are a few problems, though: Memory Leaking You provide a bi_new() function, but nothing to free any of the memory that you allocate. Any time you ...


15

Converting everything via a float means that you get the wrong result whenever the input cannot be represented exactly as a double-precision floating-point number. For example, this is surely not acceptable: >>> StrictInt(10**23) 99999999999999991611392 There's an OverflowError when the input is too large to be represented as a float: >>>...


14

A couple of comments first It would be better to let your divide method should return an int, not do the output to System.out itself. Do the output in main like this: public static void main(String[] args) { System.out.println(divide(-4,-10)); } The variables N and D are short and don't follow the Java naming conventions. Parameter names should start ...


14

First of all, yes, CortexM0 lacks any way to do 32x32=64 multiplication in hardware. CortexM3 and CortexM4 have the umull instruction, which lets you do 32x32=64 really easily. And yes, since you're writing in C, one possible implementation would be uint64_t mul32x32(uint32_t r0, uint32_t r1) { return r0*(uint64_t)r1; } but I assume you've already tried ...


14

Unless you wish to optimize the code, with specialized swappers for various hosts orders, you are doing it wrong. I invite you to check The Byte Order Fallacy by Rob Pike. The punch line: the byte order of the computer you are executing the code on doesn't matter, because the language abstracts it for you. Thus, only the byte order of the network matters, ...


14

You should probably add IConvertible restriction on T, since it is used by Convert.ChangeType method. Also this check: typeof(T) == x.GetType() looks like an overhead. Convert.ChangeType does nothing if types match. For example, check out Int32 sources: int IConvertible.ToInt32(IFormatProvider provider) { return m_value; } So you might as well just ...


14

It incorrectly returns false when the input is 1. \$2^0 = 1\$ Looping up to number is very inefficient. For example if number is two billion, it'll loop two billion times, but you'd only need about log2(number) iterations, or simply hardcode the range 0 to 30, since the input is a 32-bit integer. Mixing floating point and integers is difficult to reason ...


13

Instead of using a map, you can get the corresponding digits directly by subtracting the character code of '۰'. That is, since the character code of '۳' is 1779 and the character code of '۰' is 1776, you can calculate that: '۳'.charCodeAt(0) - '۰'.charCodeAt(0) = 1779 - 1776 = 3 Using the above logic, the function can be written shorter: String.prototype....


13

Wrong flag I believe you should be looking at the overflow flag instead of the carry flag, since all of your operands are signed values. On x86, the overflow flag is set if signed addition overflows. The carry flag is set if unsigned addition overflows. Not reliable As @Edward pointed out, it doesn't seem reliable to use this kind of function because ...


13

Reviewing your current structure: your return ""; could be improved: it should / could be inside the switch statement as a default case. It's better to use an object here, as later you can extend it without having to spend pointless LoCs on cases and breaking. function arabicToGreek(input) { 'use strict'; var greek = { 1: "α", 2: "β"...


13

It's great to see that you're using strict mode for strict compliance (which should really be the default), however you shouldn't use strict mode the way you are now. You've probably seen strict mode placed inside of functions, but those functions are IIFEs (Immediately Invoked Function Expressions) - it looks a bit like this. (function() { 'use strict' }(...


13

Compiler errors First of all, this code does not compile with the (IMO too lenient) command line of : gcc -Wall -Werror main.c -o strtol Instead it gives the message that @vnp showed in their answer, that you should change if (number[0] = '0') to either if ( (number[0] = '0') ) or to if (number[0] == '0'). Having said that, the command line I usually use ...


Only top voted, non community-wiki answers of a minimum length are eligible