📝
marcyannotes
  • Welcome
  • Student Guidelines & Policies
    • Student Handbook
    • AI Policy
    • Academic Calendar
  • Environment Setup
    • Local Environment Setup - Mac
    • Local Environment Setup - Windows
    • GitHub Setup
    • Postgres Setup
  • Fullstack Software Engineering Curriculum
    • Overview
    • How-Tos
      • How To Code at Marcy: Code Style Guide
      • How to Do Short Response and Coding Assignments
      • How to Debug
      • How to PEDAC
      • How to Create Projects with Vite
      • How to Deploy on GitHub Pages
      • How to Deploy on Render
    • Mod 0 - Command Line Interfaces, Git, and GitHub
      • Mod 0 Overview
      • Command Line Interfaces
      • Git & GitHub
      • Git Pulling & Merging
      • Git Branching & PRs
      • Pair Programming: BONUS
    • Mod 1 - JavaScriptFundamentals
      • Mod 1 Overview
      • Intro to Programming
      • Errors
      • Node & Node Modules
      • Variables, Functions & String Methods
      • Control Flow, typeof, and Math
      • Loops
      • Arrays
      • Objects
      • Higher Order Functions: Callbacks
      • Higher Order Functions: Array Methods
      • Regex
    • Mod 2 - HTML, CSS & the DOM
      • Mod 2 Overview
      • HTML
      • CSS
      • Accessibility (a11y)
      • The DOM
      • Events
      • Forms
      • The Box Model and Positioning
      • Flexbox
      • Grid & Media Queries
      • ESModules
      • LocalStorage
    • Mod 3 - Async & APIs
      • Mod 3 Overview
      • Promises
      • Fetch
      • Building a Fetching App
      • Async & Await
    • Mod 4 - Project Week!
      • Project Week Overview
    • Mod 5 - Object-Oriented Programming
      • Mod 5 Overview
      • Intro to OOP, Encapsulation, Factory Functions, and Closure
      • Classes
      • Private & Static
      • Has Many/Belongs To
      • Polymorphism
    • Mod 6 - Data Structures & Algorithms
      • Mod 6 Overview
      • Stacks & Queues
      • Nodes & Linked Lists
      • Singly & Doubly Linked Lists
      • Recursion
      • Trees
    • Mod 7 - React
      • Mod 7 Overview
      • Intro to React
      • Events, State, and Forms
      • Fetching with useEffect
      • Building a Flashcards App
      • React Context
      • Global Context Pattern
      • React Router
    • Mod 8 - Backend
      • Mod 8 Overview
      • Intro to Express
      • Building a Static Web Server with Middleware
      • Securing API Keys with Environment Variables
      • Building a RESTful API with MVC
      • SQL and Databases
      • JOIN (Association) SQL Queries
      • Knex
      • Your First Fullstack App!
      • Migrations & Seeds
      • Schema Design & Normalization
      • Hashing Passwords with Bcrypt
  • Code Challenge Curriculum
    • Unit 0
      • Lecture: Functions in JS
      • CC-00: Functions and Console Logs
      • CC-01: Conditionals
      • CC-02: Conditionals 2
    • Unit 1
      • CC-03: For Loops
      • CC-04: For Loops and Conditionals
      • CC-05: For Loops and Conditionals 2
    • Unit 2
      • CC-06: String Mutations
      • CC-07: Array Iteration
      • CC-08: String Mutation and Array Iteration
      • CC-09: Array Mutations
      • CC-10: Reading Objects
      • CC-11: Objects
      • CC-12: Objects
      • Unit 2 Diagnostic
    • Unit 3
      • Intro to PEDAC (and Algorithms)
      • validTime
      • fizzBuzz (array)
      • digitSumDifference
      • firstNotRepeating
      • compareEvenAndOddSum
      • countVowelConsonants
      • finalHP
      • canMakeTriangle
    • Unit 4
    • Unit 5
    • Unit 6
    • Unit 7
    • Unit 8
    • Sorting
Powered by GitBook
On this page
  • Code Challenge
  • Using methods...
  • Simple no-method approach
  1. Code Challenge Curriculum
  2. Unit 3

digitSumDifference

with Carmen Salas • 2024/11/04

Code Challenge

Using methods...

/*
## PEDAC
**Problem**
Parse a number into individual digits and output the difference between the sum of all evens and all odds.
Number -> Number indicating the difference (as described above)

**Examples/Edge Cases:** 
2134 -> 6 (evens) - 4 (odds) == 2

**Data Structure**
- Number
- String
- Array

**Algorithm** 
1. Convert number into string.
2. Split string into array.
3. Convert each item into a number.
4. Look at each number in the array: if even, add value to sum, else subtract value from sum.
*/
function solution(n) {
  // method approach
  return [...String(n)] // step 1 and 2
           .reduce((sum, val) => // step 3 and 4
             // loose equality for type conversion
             (val%2 == 0) ? sum+Number(val) : sum-Number(val), 0);
}

Simple no-method approach

/*
## PEDAC
**Problem**
- Given a Number, look at each digit individually and sum all the evens and all the odds. The result will be the difference between sumEvens-sumOdds.
- We can skip the need for two sums because we notice that:
    all evens are additive, while
    all odds are subtractive.
- Meaning, we can just add all evens and subtract all odds to get the sum.

**Examples/Edge Cases:** 
input: 1234 => 1 , 2 , 3 , 4 => sum(2,4) - sum(1,3) => 2
               ^   ^   ^   ^    ^          ^           ^
               look at each     evens      odds        result
               
**Data Structures**
- Number
- While loops
- Conditional (ternary in this case)

**Algorithm** 
While n > 0, for each iteration:
  - do n%10 (this takes the value of the `ones` place)
  - if n%10 is even, ADD it to sum
                odd, SUBTRACT it from sum
  - do n // 10 (integer division)
Return the resulting sum.

Walkthrough for input = 1234
----------------------------
While (n > 0) loop:
  1st loop: sum = 0
    1234 % 10 => 4
    4 is even, sum += 4   
    1234 / 10 => Math.floor(123.4) => 123
  2nd loop: sum = 4
    123 % 10 => 3
    3 is odd, sum -= 3
    123 / 10 => Math.floor(12.3) => 12
  3rd loop: sum = 1
    12 % 10 => 2
    2 is odd, sum += 2
    12 / 10 => Math.floor(1.2) => 1
  4th loop: sum = 3
    1 % 10 => 1
    1 is odd, sum -= 1
    1 / 10 => Math.floor(0.1) => 0
Exit loop with sum = 2.
*/

function solution(n) {
  let sum = 0; // initialize the sum
  while (n > 0) {
    const rem = n%10; // remainder by 10 is effectively the number in the `ones` place
    (rem%2 === 0) ? sum += rem : sum -= rem; // add if even, subtract if odd
    n = Math.floor(n/10); // integer division, to remove the `ones` number we just processed
  }
  return sum; // return the sum
}
PreviousfizzBuzz (array)NextfirstNotRepeating

Last updated 7 months ago